調用宜遠ai測膚接口-multipart方式上傳圖片(HttpURLConnection)
官網:https://api.yimei.ai/apimgr/#/api/home
官方文檔:https://api.yimei.ai/apimgr/static/help.html
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.setting.dialect.Props;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import static com.ryc.taobaoapi.util.names.skindetectnames.YiMeiNames.URL_REQ_PARAM;
/**
* 宜遠api調用工具
*/
public class TeskSkinUtils {
private static String YIMEI_CLIENT_ID = "向平臺申請的應用ID";
private static String YIMEI_CLIENT_SECRET = "向平臺申請的密鑰";
private static int TIME_OUT = 10 * 1000; //超時時間
private static String CHARSET = "utf-8"; //設置編碼
public static void main(String[] args) throws FileNotFoundException {
System.out.println("===========");
// System.out.println(TeskSkinUtils.testSkinWithFile("/工作/aaaa.jpg"));
InputStream inputStream = new FileInputStream("/工作/aaaa.jpg");
System.out.println(TeskSkinUtils.testSkinWithInputStream(inputStream));
System.out.println("===========");
}
/**
* 調用宜遠ai測膚接口
*
* @param inputStream 需要上傳的文件
* @return 返回響應的內容
*/
public static String testSkinWithInputStream(InputStream inputStream) {
Map<String, String> param = new HashMap<>();
String RequestURL = "https://api.yimei.ai/v2/api/face/analysis/" + URL_REQ_PARAM;
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); //邊界標識 隨機生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; //內容類型
String imageName=UUID.randomUUID().toString()+"_.jpg";
InputStream input=null;
DataOutputStream dos = null;
try {
Props propLoadCache = PropsUtil.getPropLoadCache();
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); //允許輸入流
conn.setDoOutput(true); //允許輸出流
conn.setUseCaches(false); //不允許使用緩存
conn.setRequestMethod("POST"); //請求方式
conn.setRequestProperty("Charset", CHARSET); //設置編碼
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
String client_id = propLoadCache.getStr("YIMEI_CLIENT_ID", YIMEI_CLIENT_ID);
String client_secret = propLoadCache.getStr("YIMEI_CLIENT_SECRET", YIMEI_CLIENT_SECRET);
conn.setRequestProperty("Authorization", "Basic " + new sun.misc.BASE64Encoder().encode((client_id+":"+client_secret).getBytes()));
if (inputStream != null) {
/**
* 當文件不爲空,把文件包裝並且上傳
*/
dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = new StringBuffer();
String params = "";
if (param != null && param.size() > 0) {
Iterator<String> it = param.keySet().iterator();
while (it.hasNext()) {
sb = null;
sb = new StringBuffer();
String key = it.next();
String value = param.get(key);
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"")
.append(key)
.append("\"")
.append(LINE_END)
.append(LINE_END);
sb.append(value).append(LINE_END);
params = sb.toString();
dos.write(params.getBytes());
}
}
sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 這裏重點注意:
* name裏面的值爲服務器端需要key 只有這個key 纔可以得到對應的文件
* filename是文件的名字,包含後綴名的 比如:abc.png
*/
sb.append("Content-Disposition: form-data; name=\"")
.append("image")
.append("\"")
.append(";filename=\"")
.append(imageName)
.append("\"\n");
sb.append("Content-Type: image/png");
sb.append(LINE_END).append(LINE_END);
dos.write(sb.toString().getBytes());
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
dos.write(end_data);
dos.flush();
/**
* 獲取響應碼 200=成功
* 當響應成功,獲取響應的流
*/
int res = conn.getResponseCode();
System.out.println("res=========" + res);
if (res == 200) {
input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
} else {
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//關閉流
try {
if (inputStream!=null) inputStream.close();
} catch (IOException e) {}
try {
if (input!=null) input.close();
} catch (IOException e) {}
try {
if (dos!=null) dos.close();
} catch (IOException e) {}
}
return result;
}
/**
* 調用宜遠ai測膚接口
*
* @param filePath 需要上傳的文件
* @return 返回響應的內容
*/
public static String testSkinWithFile(String filePath) {
File file = new File(filePath);
Map<String, String> param = new HashMap<>();
String RequestURL = "https://api.yimei.ai/v2/api/face/analysis/" + URL_REQ_PARAM;
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); //邊界標識 隨機生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; //內容類型
String imageName=System.currentTimeMillis()+"_"+file.getName();
InputStream input=null;
InputStream is =null;
DataOutputStream dos = null;
try {
Props propLoadCache = PropsUtil.getPropLoadCache();
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); //允許輸入流
conn.setDoOutput(true); //允許輸出流
conn.setUseCaches(false); //不允許使用緩存
conn.setRequestMethod("POST"); //請求方式
conn.setRequestProperty("Charset", CHARSET); //設置編碼
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
String client_id = propLoadCache.getStr("YIMEI_CLIENT_ID", YIMEI_CLIENT_ID);
String client_secret = propLoadCache.getStr("YIMEI_CLIENT_SECRET", YIMEI_CLIENT_SECRET);
conn.setRequestProperty("Authorization", "Basic " + new sun.misc.BASE64Encoder().encode((client_id+":"+client_secret).getBytes()));
if (file != null) {
/**
* 當文件不爲空,把文件包裝並且上傳
*/
dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = new StringBuffer();
String params = "";
if (param != null && param.size() > 0) {
Iterator<String> it = param.keySet().iterator();
while (it.hasNext()) {
sb = null;
sb = new StringBuffer();
String key = it.next();
String value = param.get(key);
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"")
.append(key)
.append("\"")
.append(LINE_END)
.append(LINE_END);
sb.append(value).append(LINE_END);
params = sb.toString();
dos.write(params.getBytes());
}
}
sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 這裏重點注意:
* name裏面的值爲服務器端需要key 只有這個key 纔可以得到對應的文件
* filename是文件的名字,包含後綴名的 比如:abc.png
*/
sb.append("Content-Disposition: form-data; name=\"")
.append("image")
.append("\"")
.append(";filename=\"")
.append(imageName)
.append("\"\n");
sb.append("Content-Type: image/png");
sb.append(LINE_END).append(LINE_END);
dos.write(sb.toString().getBytes());
is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
dos.write(end_data);
dos.flush();
/**
* 獲取響應碼 200=成功
* 當響應成功,獲取響應的流
*/
int res = conn.getResponseCode();
System.out.println("res=========" + res);
if (res == 200) {
input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
} else {
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//關閉流
try {
if (is!=null) is.close();
} catch (IOException e) {}
try {
if (input!=null) input.close();
} catch (IOException e) {}
try {
if (dos!=null) dos.close();
} catch (IOException e) {}
}
return result;
}
/** 宜遠測膚接口 */
public static JSONObject testSkinWithUrl(String resourceUrl) {
try {
Props propLoadCache = PropsUtil.getPropLoadCache();
String url = "https://api.yimei.ai/v2/api/face/analysis/" + URL_REQ_PARAM;
String client_id = propLoadCache.getStr("YIMEI_CLIENT_ID", YIMEI_CLIENT_ID);
String client_secret = propLoadCache.getStr("YIMEI_CLIENT_SECRET", YIMEI_CLIENT_SECRET);
String body="image=" + resourceUrl;
HttpURLConnection httpURLConnection = (HttpURLConnection)new URL(url).openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod(ServletUtil.METHOD_POST);
httpURLConnection.setRequestProperty(Header.CONTENT_TYPE.toString(), ContentType.FORM_URLENCODED.toString());
httpURLConnection.setRequestProperty("Authorization", "Basic " + new sun.misc.BASE64Encoder().encode((client_id+":"+client_secret).getBytes()));
httpURLConnection.setRequestProperty(Header.CONTENT_LENGTH.toString(), String.valueOf(body.length()));
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine;
try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(body);
outputStreamWriter.flush();
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (outputStreamWriter != null){outputStreamWriter.close();}
if (outputStream != null){outputStream.close();}
if (reader != null){reader.close();}
if (inputStreamReader != null){inputStreamReader.close();}
if (inputStream != null){inputStream.close();}
}
return JSONObject.parseObject(resultBuffer.toString());
} catch (Exception e) {
LogUtil.sysLog.error("yimeiSkin-e={}, st={}", e, StringUtils.join(e.getStackTrace()));
}
return null;
}
}