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

调用宜远ai测肤接口-multipart方式上传图片(HttpURLConnection)相关推荐

  1. 测肤API+应用开发,自助打开线上AI测肤

    现在AI应用的项目越来越多,人脸识别,语音识别,实物分类等,会软件开发的你, 是不是也曾想过开发自己的AI应用项目,却止步于不会AI算法开发呢.不要急,各大AI公司提供的API便或许能满足你的需求. ...

  2. 宜远公众号H5网页AI测肤报告分享

    发现网上找的H5网页分享功能的资料都不够详细. 拿宜远H5网页AI测肤报告分享为例,整理一下H5网页微信分享给朋友和分享朋友圈的功能 1.加载微信的jssdk //微信h5      import w ...

  3. 首次揭秘美图影像实验室MTlab:发布AI测肤技术、所有产品围绕用AI让你更美

    作者|震霆 出品|遇见人工智能(公众号:gowithai) 独家 福利|点标题下蓝字,或微信搜"遇见人工智能",关注后回复"报告",1秒钟获取麦肯锡.德勤等48 ...

  4. 逃离AI测肤“美学陷阱”:体素科技手握严肃皮肤病AI宝藏图

    近年以来,"皮肤管理"成为了一个很流行的词汇.一提起皮肤管理的概念,我们似乎就想到遍地开花的美容机构,以及小气泡.美黑等一系列名词.确实随着生活水平的普遍提高,人们对于皮肤管理的需 ...

  5. AI测肤:不再止步于”表面美颜”

    从近几年的中国护肤品市场销量来看,近几年女性对于护肤产品,护肤服务的消费都在逐年提升.在过去的两年里,国家就已经开始提出了AI.5G.区块链等关键词,这也预示着这些关键词将会是改变我们未来的关键. 先 ...

  6. ai皮肤检测分数_上线俩月,完成2300多万次皮肤测试;找出皮肤问题?AI测肤技术准确率达95%...

    (图为:美图美妆的产品总监易静) 对大多数女性而言,皮肤问题常伴始终.冬天干燥,夏天出游,护肤品换了一轮又一轮,也没找到真正适合自己的产品.12月21日,美图公司AI研究中枢--美图影像实验室MTla ...

  7. 在娱乐化和专业化两端的AI测肤,未来到底应该往哪走?

    相信在这个世界上,没人不惧怕衰老.由此也衍生出出了极具价值的"抗老经济",女性的医美.护肤.化妆品,男性的食补.撸铁.马拉松.尤其在脸,这个衰老最明显的部位上,人们甚至会做出一些非 ...

  8. AI测肤,你今天真好看

    大概五六年前退学回国的时候,我就想,如果将来要做一件可以立业的事,我希望可以影响一千万人,然后就有了"你今天真好看"APP. 前两天看了一下下载量,居然真的有一千多万了. 吴亮,计 ...

  9. AI看脸、测肤,左可美妆新零售,右能智慧医美

    本文来自AI新媒体量子位(QbitAI) 如果你跟我一样不喜欢XX氏里的那些护肤导购,新年好消息,AI又要来送温暖了. 至少你皮肤好不好.怎么样.该用什么样的护肤品这件事,再也不用被大庭广众有感情宣读 ...

最新文章

  1. 【Java源码分析】LinkedHashSet和HashSet源码分析
  2. 安信可ESP-12F(ESP8266)介绍与使用
  3. JS中点语法和方括号语法访问属性的区别
  4. 大话后端开发的奇淫技巧大集合
  5. 【译】 WebSocket 协议第八章——错误处理(Error Handling)
  6. thinkphp3.2.3版本的数据库增删改查实例
  7. java树洞_SSM框架开发案例——铁大树洞后台管理系统
  8. 山西农业大学c语言程序设计试卷答案,2016年宁夏医科大学公共卫生与管理学院C语言程序设计(加试)复试笔试最后押题五套卷...
  9. 中控考勤机-C#操作
  10. Python使用在线接口SDK模块(baidu-aip)实现人脸识别
  11. 记忆中的巷子与老房子
  12. 本周最新文献速递20220123
  13. FireStart教程:基于SharePoint的出差报销流程六
  14. 工作后,又想读个名校的计算机硕士,该怎么做?
  15. LaTeX会议论文添加版权信息
  16. mysql5.0忘记root密码_【咨询】mysql忘记root密码的处理方法(5.5/5.0)
  17. 前端之HTML基础扫盲
  18. 更新微信 7.0,你后悔了吗?
  19. 将GBK格式的文件转为UTF-8格式,避免中文乱码
  20. 组合式 API如何解决vue2中mixin的局限性?

热门文章

  1. 扫描线算法讲解+例题
  2. 大数据面试八股文之 hive 篇
  3. 小学计算机键盘的初步认识教案,小学信息技术西交大三(上)第六课:初步认识键盘(教案...
  4. 敏感性与特异性、查准率和查全率
  5. redhat 安装redash
  6. Java解决程序包不存在的问题
  7. 职业对口升学计算机英语2016,2016河南对口升学(英语)
  8. 论产品设计师的自我修养
  9. 检测域名是否已被微信封掉不能访问
  10. APIJSON使用和搭建