调用宜远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 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 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 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 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;
}
}