此篇 java 文章是基于聚合数据 (http://www.juhe.cn)—– 证件辨认接口来演示,根本 HTTP POST 申请上传图片并接管 JSON 数据来解决,其余与上传图片相干的接口申请可参考此篇文章。
应用前你须要:
①:通过 http://www.juhe.cn/docs/api/id/153 申请一个名片辨认的 appkey
1. 反对的证件类型清单
此接口可通过 GET 申请失去后果,java 网络申请有 HttpClient 相干工具包及 HttpURLConnection 相干的包等,这里用的是 HttpClient,须要先导包,如果用 maven 话会更不便间接把:
org.apache.httpcomponents
httpmime
4.3.6
org.apache.httpcomponents
httpclient
4.4.1
复制到配置文件 pom.xml
申请代码如下:
public static String get() throws IOException {
// 创立 HttpClient 对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result = null;
try {HttpGet httpGet = new HttpGet("http://api2.juheapi.com/cardrecon/supportlist?key="+ appKey);
// 执行网络申请
response = httpClient.execute(httpGet);
// 获取申请实体
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
// ConverStreamToString 是上面写的一个办法是把网络申请的字节流转换为 utf8 的字符串
result = ConvertStreamToString(resEntity.getContent(), "UTF-8");
}
EntityUtils.consume(resEntity);
} catch (Exception e) {
} finally {
// 敞开申请
response.close();
httpClient.close();}
// 失去的是 JSON 类型的数据须要第三方解析 JSON 的 jar 包来解析
return result;
}
2. 证件图片辨认
// 此办法是 POST 申请上传的参数中蕴含本地图片信息 File 类型
public static String post(String type, File file) throws Exception {CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result = null;
// HttpClient 申请的相干设置,能够不必配置,用默认的参数,这里设置连贯和超时时长 (毫秒)
RequestConfig config = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build();
try {HttpPost httppost = new HttpPost("http://api2.juheapi.com/cardrecon/upload");
// FileBody 封装 File 类型的参数
FileBody bin = new FileBody(file);
// StringBody 封装 String 类型的参数
StringBody keyBody = new StringBody(key, ContentType.TEXT_PLAIN);
StringBody typeBody = new StringBody(type, ContentType.TEXT_PLAIN);
// addPart 将参数传入,并指定参数名称
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("pic", bin).addPart("key", keyBody)
.addPart("cardType", typeBody).build();
httppost.setEntity(reqEntity);
httppost.setConfig(config);
// 执行网络申请并返回后果
response = httpClient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {result = ConvertStreamToString(resEntity.getContent(), "UTF-8");
}
EntityUtils.consume(resEntity);
} finally {response.close();
httpClient.close();}
// 失去的是 JSON 类型的数据须要第三方解析 JSON 的 jar 包来解析
return result;
}
// 此办法是把传进的字节流转化为相应的字符串并返回,此办法个别在网络申请中用到
public static String ConvertStreamToString(InputStream is, String charset)
throws Exception {StringBuilder sb = new StringBuilder();
try (InputStreamReader inputStreamReader = new InputStreamReader(is,charset)) {try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line = null;
while ((line = reader.readLine()) != null) {sb.append(line).append("\r\n");
}
}
}
return sb.toString();}
原文链接:https://blog.csdn.net/weixin_…