发布于2020-11-19 20:51 阅读(1334) 评论(0) 点赞(17) 收藏(0)
最近在写证照识别业务,其中证照识别的接口是在调研用,选择了face++的,因为可支持自定义模板,等我有空的时候,会把全部业务流程整理出来,这里先把调用外部接口的方法写了出来。
示例代码:
JSONObject jsonObject = InterfaceUtil.doPost(TEMPLATE_OCR_URL,
buildTextMap(), buildFileMap(file));
// 传入api_key、api_secret这两个参数,类型为字符串。
private Map<String, String> buildTextMap() {
Map<String, String> textMap = new HashMap<String, String>();
textMap.put("api_key", API_KEY);
textMap.put("api_secret", API_SECRET);
return textMap;
}
// 传一个叫image_file的MultipartFile格式参数。
private Map<String, MultipartFile> buildFileMap(MultipartFile file) {
Map<String, MultipartFile> fileMap = new HashMap<String, MultipartFile>();
fileMap.put("image_file", file);
return fileMap;
}
工具类:
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.rocketmq.shade.com.alibaba.fastjson.JSONObject;
public class InterfaceUtil {
/**
* 表单形式上传数据
*
* @param urlStr 接口地址
* @param textMap 字符串参数
* @param fileMap 文件参数
* @param contentType 没有传入文件类型默认采用application/octet-stream
* contentType非空采用filename匹配默认的图片类型
* @return 返回response数据
*/
@SuppressWarnings("rawtypes")
public static JSONObject doPost(String urlStr, Map<String, String> textMap,
Map<String, MultipartFile> fileMap) {
JSONObject jsonObject = null;
HttpURLConnection conn = null;
// boundary就是request头和上传文件内容的分隔符
String BOUNDARY = "---------------------------123821742118716";
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// text
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition:form-data;name=\"" + inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
out.write(strBuf.toString().getBytes());
}
// file
if (fileMap != null) {
Iterator iter = fileMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
MultipartFile inputValue = (MultipartFile) entry.getValue();
if (inputValue == null) {
continue;
}
String filename = inputValue.getOriginalFilename();
// 没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
String contentType = inputValue.getContentType();
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition:form-data;name=\"" + inputName + "\";filename=\"" + filename
+ "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
InputStream in = inputValue.getInputStream();
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
}
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 读取返回数据
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = conn.getInputStream().read(buffer)) != -1) {
bStream.write(buffer, 0, len);
}
jsonObject = JSONObject.parseObject(new String(bStream.toByteArray(), "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return jsonObject;
}
}
作者:小胖子爱java
链接:http://www.javaheidong.com/blog/article/852/a80cde0622d1e720880d/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!