1.先创建AliyunHttpUtils
下载地址: https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
代码如下:
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class AliyunHttpUtils {
/**
* get
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* post 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 {
HttpClient httpClient = wrapClient(host);
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 {
HttpClient httpClient = wrapClient(host);
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);
}
/**
* Post stream
*
* @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,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(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);
}
/**
* Put stream
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
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();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}
2.再创建封装接口AliyunApi
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zy.common.utils.AliyunHttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component("aliyunApi")
public class AliyunApi {
/**
* 三网手机号查询
*
* @param querys idCard 身份证号
* name姓名
* needBelongArea 需要地理位置与否 true false
* phone 手机号
* @param appcode 你的Appcode
* @return
*/
public ApiResult auditphone(Map<String, String> querys,String appcode) {
// return ApiResult.error(-3,"aaaa","");
String host = "https://auditphone.showapi.com";
String path = "/phoneAudit";
String method = "GET";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
try {
HttpResponse response = AliyunHttpUtils.doGet(host, path, method, headers, querys);
String res=EntityUtils.toString(response.getEntity());
JSONObject result = JSON.parseObject(res);
if (result.isEmpty()|| !result.containsKey("showapi_res_body")) {
return ApiResult.error(-2, "接口调用失败", result.toString());
}
JSONObject resBody= JSON.parseObject(result.get("showapi_res_body").toString());
if (resBody.isEmpty()|| !resBody.containsKey("ret_code") ||!"0".equals(resBody.get("ret_code").toString())){
return ApiResult.error(-2, resBody.get("msg").toString(), result.toString());
}
return ApiResult.ok(resBody.get("msg").toString(), resBody, res.toString());
} catch (Exception e) {
return ApiResult.error(-3,e.getMessage(),"");
}
}
/**
* 印刷文字识别_身份证识别
*
* @param param pic 身份证照片base64编码 side 正面反面
* @param appcode 你的Appcode
* @return
*/
public ApiResult ocr_idcard(Map<String, String> param,String appcode) {
String host = "http://dm-51.data.aliyun.com";
String path = "/rest/160601/ocr/ocr_idcard.json";
//如果文档的输入中含有inputs字段,设置为True, 否则设置为False
Boolean is_old_format = false;
//请根据线上文档修改configure字段
JSONObject configObj = new JSONObject();
configObj.put("side", param.get("side"));
String config_str = configObj.toString();
String method = "POST";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
Map<String, String> querys = new HashMap<String, String>();
// 对图像进行base64编码
String[] pic = param.get("pic").toString().split(";base64,");
String imgBase64 = pic[1];
// 拼装请求body的json字符串
JSONObject requestObj = new JSONObject();
try {
if(is_old_format) {
JSONObject obj = new JSONObject();
obj.put("image", getParam(50, imgBase64));
if(config_str.length() > 0) {
obj.put("configure", getParam(50, config_str));
}
JSONArray inputArray = new JSONArray();
inputArray.add(obj);
requestObj.put("inputs", inputArray);
}else{
requestObj.put("image", imgBase64);
if(config_str.length() > 0) {
requestObj.put("configure", config_str);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
String bodys = requestObj.toString();
try {
HttpResponse response = AliyunHttpUtils.doPost(host, path, method, headers, querys, bodys);
int stat = response.getStatusLine().getStatusCode();
if(stat != 200){
System.out.println("Http code: " + stat);
System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message"));
String re=EntityUtils.toString(response.getEntity());
System.out.println("Http body error msg:" +re );
return ApiResult.error(-2,"请求失败",re);
}
String res = EntityUtils.toString(response.getEntity());
JSONObject res_obj = JSON.parseObject(res);
JSONObject result;
if(is_old_format) {
JSONArray outputArray = res_obj.getJSONArray("outputs");
String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
result=JSON.parseObject(output);
System.out.println(result.toJSONString());
}else{
result=res_obj;
System.out.println(result.toJSONString());
}
if (result == null || !("true".equals(result.get("success").toString()))) {
return ApiResult.error(-2, "查询失败", result.toJSONString());
}
return ApiResult.ok("查询成功", result, result.toJSONString());
} catch (Exception e) {
e.printStackTrace();
return ApiResult.error(-3,e.getMessage(),"");
}
}
/*
* 获取参数的json对象
*/
public static JSONObject getParam(int type, String dataValue) {
JSONObject obj = new JSONObject();
try {
obj.put("dataType", type);
obj.put("dataValue", dataValue);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
}
3附加接口返回统一实体ApiResult
import com.zy.common.utils.OpConstant;
import org.apache.commons.lang.StringUtils;
import java.util.Map;
/**
* 运营商api返回实体类
*
* @author Troy gch_xtkd@126.com
*/
public class ApiResult {
/**
* 错误码:0-成功 非0-失败
* -1 : 参数错误
* -2 : 接口错误
* -3 : 解析数据错误
* -4 : 该接口暂不支持
* -5 : 平台已经关闭运营商接口访问
* -6 : 未知错误
* -7 : 未知错误
* -8 : 未知错误
*/
private int status;
// 错误信息: 错误码对应的错误描述,参考错误码列表
private String message;
// 返回结果集(解析后的结果集)
public Map result;
// 返回结果集(运营商接口返回的数据)
private String apiResult;
// 运营商
private int operator;
// 运营商子类
private int opType;
public int getStatus() {
return status;
}
public boolean isSuccess(){
return status == 0;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Map getResult() {
return result;
}
public void setResult(Map result) {
this.result = result;
}
public String getApiResult() {
return apiResult;
}
public void setApiResult(String apiResult) {
this.apiResult = apiResult;
}
public static ApiResult error(int code, String msg,String apiResult) {
ApiResult r = new ApiResult();
r.setStatus(code);
r.setMessage(msg);
r.setApiResult(apiResult);
return r;
}
public static ApiResult ok(String msg,Map result,String apiResult) {
ApiResult r = new ApiResult();
r.setStatus(0);
r.setMessage(msg);
r.setResult(result);
r.setApiResult(apiResult);
return r;
}
/**
* 不支持的接口
* @return
*/
public static ApiResult unSupportApi(){
ApiResult ret = new ApiResult();
ret.setStatus(-4);
ret.setMessage("该接口暂不支持");
return ret;
}
}