最近在写证照识别业务(分析上传图片类型->调用该类型对应识别接口),其中第一步分析类型用的是TensorFlow训练出来的模型,接着用java调用其生成的pb文件进行识别类型;接着进行证照识别的接口是在调研后选择了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;
}
原工具类(返回状态码非200时会报错,优化后代码在下面):
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;
}
}
————–后续补充2020年11月20日 10:07:08————–
调试时发现,当返回的状态码不等于200时,会报错,猜测是获取流的方式有些不一样,又找到一篇文章,果然是这样,解决方案:报错时通过 getErrorStream获取错误信息,文章链接
httpurlconnection post请求获取返回码为400的异常信息
优化后工具类:
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
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();
InputStream inputStream = null;
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK ) {
inputStream = conn.getErrorStream();//主要就是这里
} else {
inputStream = conn.getInputStream();//主要就是这里
}
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
buffer.append(line);
}
String result = new String(buffer);
jsonObject = JSONObject.parseObject(result);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return jsonObject;
}
}
版权声明:本文为qq_39380155原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。