maven
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.83version>
<scope>compilescope>
dependency>
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>4.5.3version>
dependency>
HttpUtil 工具类
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpStatus;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
public class HttpUtil {
public static String doGet(String url) throws Exception {
return doGet(url, null);
}
public static String doGet(String urlPath, HashMap<String, Object> params)
throws Exception {
StringBuilder sb = new StringBuilder(urlPath);
if (params != null && !params.isEmpty()) { // 说明有参数
sb.append("?");
Set<Map.Entry<String, Object>> set = params.entrySet();
for (Map.Entry<String, Object> entry : set) { // 遍历map里面的参数
String key = entry.getKey();
String value = "";
if (null != entry.getValue()) {
value = entry.getValue().toString();
// 转码
value = URLEncoder.encode(value, "UTF-8");
}
sb.append(key).append("=").append(value).append("&");
}
sb.deleteCharAt(sb.length() - 1); // 删除最后一个&
}
URL url = new URL(sb.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000); // 5s超时
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpStatus.OK.value()) {// HttpStatus.SC_OK ==
// 200
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sbs = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sbs.append(line);
}
return sbs.toString();
}
return null;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPost(String url, Map<String, Object> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key).toString());
}
}
URI uri = builder.build();
// 创建http Post请求
HttpPost httpPost = new HttpPost(uri);
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* post form
* 以form表单的方式提交
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* Post String
* 以字符串的方式提交
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
}
具体代码
/**
* 阿里OCR身份证识别
*
* @param type 身份证正反面类型:face/back
* @param imgFile 身份证图片路径
* @return
*/
public static void ocrIdCardAli(String type, String imgFile) {
String host = "https://cardnumber.market.alicloudapi.com";
String path = "/rest/160601/ocr/ocr_idcard.json";
String appcode = "";//你的 appcode
String method = "POST";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
//根据API的要求,定义相对应的Content-Type
headers.put("Content-Type", "application/json; charset=UTF-8");
Map<String, String> querys = new HashMap<String, String>();
// 对图像进行base64编码
String imgBase64 = img_base64(imgFile);
//configure配置
JSONObject configObj = new JSONObject();
configObj.put("side", type);//身份证正反面类型:face/back
String config_str = configObj.toString();
// 拼装请求body的json字符串
JSONObject requestObj = new JSONObject();
requestObj.put("image", imgBase64);
if (configObj.size() > 0) {
requestObj.put("configure", config_str);
}
String bodys = requestObj.toString();
try {
HttpResponse response = HttpUtil.doPost(host, path, method, headers, querys, bodys);
int stat = response.getStatusLine().getStatusCode();
if (stat != 200) {
System.out.println("身份证识别失败");
return;
}
String res = EntityUtils.toString(response.getEntity());
JSONObject res_obj = JSON.parseObject(res);
if ((boolean) res_obj.get("success")) {
if (type.equals("face")) {//正面
System.out.println(res_obj.get("name"));
System.out.println(res_obj.get("num"));
System.out.println(res_obj.get("address"));
System.out.println(res_obj.get("nationality"));
System.out.println(res_obj.get("sex"));
System.out.println(res_obj.get("birth"));
} else {
System.out.println(res_obj.get("end_date"));
System.out.println(res_obj.get("issue"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String img_base64(String path) {
/**
* 对path进行判断,如果是本地文件就二进制读取并base64编码,如果是url,则返回
*/
String imgBase64 = "";
if (path.startsWith("http")) {
imgBase64 = path;
} else {
try {
File file = new File(path);
byte[] content = new byte[(int) file.length()];
FileInputStream finputstream = new FileInputStream(file);
finputstream.read(content);
finputstream.close();
imgBase64 = new String(Base64.encodeBase64(content));
} catch (IOException e) {
e.printStackTrace();
return imgBase64;
}
}
return imgBase64;
}