java騰訊AI人臉對比對接代碼實例
技術(shù)棧:
- Spring boot 2.x
- 騰訊
- java版本1.8
注意事項:
- 本文內(nèi)的“**.**”需要自己替換為自己的路徑。
- 常量內(nèi)的“**”需要自己定義自己內(nèi)容。
- 業(yè)務(wù)中認(rèn)證圖片,上傳至阿里云OSS上
話不多說,直接上代碼
1、pom文件:
<!-- apache httpclient組件 --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency> <!-- https://mvnrepository.com/artifact/com.aliyun.oss/aliyun-sdk-oss --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>2.2.1</version> </dependency>
2、人臉識別業(yè)務(wù):FaceController文件:
package com.**.**.controller;
import com.mb.initial.entity.Test;
import com.mb.initial.enums.ResultEnum;
import com.mb.initial.result.Result;
import com.mb.initial.service.IFaceService;
import com.mb.initial.util.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 人臉識別業(yè)務(wù)
* @author: yanjianghua
* @date: 2018/11/16 16:58
*/
@Api(value = "人臉識別業(yè)務(wù)",description = "人臉識別業(yè)務(wù)")
@ApiResponses(value = {@ApiResponse(code = 200, message = "success",response = Test.class)})
@RequestMapping(value = "/1.0/face",method = {RequestMethod.GET, RequestMethod.POST})
@RestController
public class FaceController {
private Logger log = LoggerFactory.getLogger(FaceController.class);
@Autowired
private IFaceService faceService;
@ApiOperation(value = "人臉對比信息接口", notes = "人臉對比信息接口")
@RequestMapping(value = "/getFaceCompare")
public Result getFaceCompare(@RequestParam(value = "imageBaseAuthentication", required = false) String imageBaseAuthentication,
@RequestParam(value = "imageBase", required = false) String imageBase,
HttpServletResponse response,
HttpServletRequest request) throws Exception{
if (imageBaseAuthentication == null || imageBase == null || "".equals(imageBase) || "".equals(imageBaseAuthentication)) {
return ResultUtils.response(ResultEnum.PARAMETER_NULL);
}
Object result = faceService.getFaceCompare(imageBaseAuthentication, imageBase);
if(result == null){
return ResultUtils.response(ResultEnum.ERROR);
}else{
return ResultUtils.response(result);
}
}
}
3、IFaceService文件:
package com.**.**.service;
/**
*
* @author: yanjianghua
* @date: 2018/11/16 16:49
*/
public interface IFaceService {
/**
* 人臉對比API接口
* @param imageBaseAuthentication
* @param imageBase
* @return
*/
public Object getFaceCompare(String imageBaseAuthentication, String imageBase);
}
4、邏輯實現(xiàn)類:IFaceServiceImpl
package com.**.**.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.**.**.constants.BaseConstants;
import com.**.**.exception.BillingException;
import com.**.**.result.HttpClientResult;
import com.**.**.service.IFaceService;
import com.**.**.util.HttpClientUtils;
import com.**.**.util.MD5Utils;
import com.**.**.util.TencentAISignUtils;
import com.**.**.util.TimeUtils;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author: yanjianghua
* @date: 2018/11/16 16:50
*/
@Service
public class IFaceServiceImpl implements IFaceService {
@Override
public Object getFaceCompare(String imageBaseAuthentication, String imageBase){
HttpClientResult result = null;
Map<String, String> params = new HashMap<String, String>();
params.put("app_id", String.valueOf(BaseConstants.APP_ID_AI_OCR));
params.put("time_stamp", String.valueOf(System.currentTimeMillis() / 1000 + ""));
params.put("nonce_str", MD5Utils.getCharAndNumr(10,3));
params.put("image_a", imageBaseAuthentication);
params.put("image_b", imageBase);
params.put("sign", "");
//獲取sign
String sign = null;
try {
//POST
sign = TencentAISignUtils.getSignature(params);
if(sign == null) {
throw new BillingException("sign錯誤") ;
}
params.put("sign", sign);
result = HttpClientUtils.doPost(BaseConstants.FACE_COMPARE_URL, params);
if(result != null) {
System.out.println("===faceCompare===:" + result.getContent());
JSONObject content = JSON.parseObject(result.getContent());
JSONObject resData = JSON.parseObject(content.getString("data"));
return resData;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
5、http工具類:HttpClientUtils
package com.**.**.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
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.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
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 com.**.**.result.HttpClientResult;
/**
* Description: httpClient工具類
*
* @author JourWon
* @date Created on 2018年11月30 日
*/
public class HttpClientUtils {
//編碼格式。發(fā)送編碼格式統(tǒng)一用UTF-8
private static final String ENCODING = "UTF-8";
//設(shè)置連接超時時間,單位毫秒。
private static final int CONNECT_TIMEOUT = 6000;
//請求獲取數(shù)據(jù)的超時時間(即響應(yīng)時間),單位毫秒。
private static final int SOCKET_TIMEOUT = 6000;
/**
* 發(fā)送get請求;不帶請求頭和請求參數(shù)
*
* @param url 請求地址
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url) throws Exception {
return doGet(url, null, null);
}
/**
* 發(fā)送get請求;帶請求參數(shù)
*
* @param url 請求地址
* @param params 請求參數(shù)集合
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
return doGet(url, null, params);
}
/**
* 發(fā)送get請求;帶請求頭和請求參數(shù)
*
* @param url 請求地址
* @param headers 請求頭集合
* @param params 請求參數(shù)集合
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 創(chuàng)建httpClient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 創(chuàng)建訪問的地址
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
// 創(chuàng)建http對象
HttpGet httpGet = new HttpGet(uriBuilder.build());
/**
* setConnectTimeout:設(shè)置連接超時時間,單位毫秒。
* setConnectionRequestTimeout:設(shè)置從connect Manager(連接池)獲取Connection
* 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連接池的。
* setSocketTimeout:請求獲取數(shù)據(jù)的超時時間(即響應(yīng)時間),單位毫秒。 如果訪問一個接口,多少時間內(nèi)無法返回數(shù)據(jù),就直接放棄此次調(diào)用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpGet.setConfig(requestConfig);
// 設(shè)置請求頭
packageHeader(headers, httpGet);
// 創(chuàng)建httpResponse對象
CloseableHttpResponse httpResponse = null;
try {
// 執(zhí)行請求并獲得響應(yīng)結(jié)果
return getHttpClientResult(httpResponse, httpClient, httpGet);
} finally {
// 釋放資源
release(httpResponse, httpClient);
}
}
/**
* 發(fā)送post請求;不帶請求頭和請求參數(shù)
*
* @param url 請求地址
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url) throws Exception {
return doPost(url, null, null);
}
/**
* 發(fā)送post請求;帶請求參數(shù)
*
* @param url 請求地址
* @param params 參數(shù)集合
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
return doPost(url, null, params);
}
/**
* 發(fā)送post請求;帶請求頭和請求參數(shù)
*
* @param url 請求地址
* @param headers 請求頭集合
* @param params 請求參數(shù)集合
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 創(chuàng)建httpClient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 創(chuàng)建http對象
HttpPost httpPost = new HttpPost(url);
/**
* setConnectTimeout:設(shè)置連接超時時間,單位毫秒。
* setConnectionRequestTimeout:設(shè)置從connect Manager(連接池)獲取Connection
* 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連接池的。
* setSocketTimeout:請求獲取數(shù)據(jù)的超時時間(即響應(yīng)時間),單位毫秒。 如果訪問一個接口,多少時間內(nèi)無法返回數(shù)據(jù),就直接放棄此次調(diào)用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
// 設(shè)置請求頭
/*httpPost.setHeader("Cookie", "");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
packageHeader(headers, httpPost);
// 封裝請求參數(shù)
packageParam(params, httpPost);
// 創(chuàng)建httpResponse對象
CloseableHttpResponse httpResponse = null;
try {
// 執(zhí)行請求并獲得響應(yīng)結(jié)果
return getHttpClientResult(httpResponse, httpClient, httpPost);
} finally {
// 釋放資源
release(httpResponse, httpClient);
}
}
/**
* 發(fā)送put請求;不帶請求參數(shù)
*
* @param url 請求地址
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url) throws Exception {
return doPut(url);
}
/**
* 發(fā)送put請求;帶請求參數(shù)
*
* @param url 請求地址
* @param params 參數(shù)集合
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPut.setConfig(requestConfig);
packageParam(params, httpPut);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpPut);
} finally {
release(httpResponse, httpClient);
}
}
/**
* 發(fā)送delete請求;不帶請求參數(shù)
*
* @param url 請求地址
* @return
* @throws Exception
*/
public static HttpClientResult doDelete(String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpDelete.setConfig(requestConfig);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpDelete);
} finally {
release(httpResponse, httpClient);
}
}
/**
* 發(fā)送delete請求;帶請求參數(shù)
*
* @param url 請求地址
* @param params 參數(shù)集合
* @return
* @throws Exception
*/
public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {
if (params == null) {
params = new HashMap<String, String>();
}
params.put("_method", "delete");
return doPost(url, params);
}
/**
* Description: 封裝請求頭
* @param params
* @param httpMethod
*/
public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
// 封裝請求頭
if (params != null) {
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
// 設(shè)置到請求頭到HttpRequestBase對象中
httpMethod.setHeader(entry.getKey(), entry.getValue());
}
}
}
/**
* Description: 封裝請求參數(shù)
*
* @param params
* @param httpMethod
* @throws UnsupportedEncodingException
*/
public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
throws UnsupportedEncodingException {
// 封裝請求參數(shù)
if (params != null) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// 設(shè)置到請求的http對象中
httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
}
}
/**
* Description: 獲得響應(yīng)結(jié)果
*
* @param httpResponse
* @param httpClient
* @param httpMethod
* @return
* @throws Exception
*/
public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
// 執(zhí)行請求
httpResponse = httpClient.execute(httpMethod);
// 獲取返回結(jié)果
if (httpResponse != null && httpResponse.getStatusLine() != null) {
String content = "";
if (httpResponse.getEntity() != null) {
content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
}
return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
}
return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
/**
* Description: 釋放資源
*
* @param httpResponse
* @param httpClient
* @throws IOException
*/
public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
// 釋放資源
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
6、http響應(yīng)類
package com.**.**.result;
import java.io.Serializable;
/**
* Description: 封裝httpClient響應(yīng)結(jié)果
* @author: yanjianghua
* @date: 2018/9/12 13:45
*/
public class HttpClientResult implements Serializable {
private static final long serialVersionUID = 2168152194164783950L;
/**
* 響應(yīng)狀態(tài)碼
*/
private int code;
/**
* 響應(yīng)數(shù)據(jù)
*/
private String content;
public HttpClientResult() {
}
public HttpClientResult(int code) {
this.code = code;
}
public HttpClientResult(String content) {
this.content = content;
}
public HttpClientResult(int code, String content) {
this.code = code;
this.content = content;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "HttpClientResult [code=" + code + ", content=" + content + "]";
}
}
7、常量類:BaseConstants
package com.**.**.constants;
/**
* 常量類
*/
public class BaseConstants {
// 默認(rèn)使用的redis的數(shù)據(jù)庫
public static final Integer ASSETCENTER_DEFAULT_FLAG = 0;
// redis的數(shù)據(jù)庫 1庫
public static final Integer ASSETCENTER_BUSNESS_FLAG = 1;
/**
* 騰訊AI對外開放平臺-APP_ID
*/
public static final int APP_ID_AI_OCR = *********;
/**
* 騰訊AI對外開放平臺-APP_KEY
*/
public static final String APP_KEY_AI_OCR = "*********";
public static final String OCR_ID_CARD_OCR_URL = "https://api.ai.qq.com/fcgi-bin/ocr/ocr_idcardocr";
public static final String OCR_CREDITCARD_OCR_URL = "https://api.ai.qq.com/fcgi-bin/ocr/ocr_creditcardocr";
public static final String FACE_COMPARE_URL = "https://api.ai.qq.com/fcgi-bin/face/face_facecompare";
public static final String ALIYUN_OSS_OBJECT_NAME_OCR = "idCardocr/";
public static final String ALIYUN_OSS_OBJECT_CREDITCARD_OCR = "creditCard/";
public static final String ALIYUN_OSS_OBJECT_AUTH_DIR = "authentication/";
}
以上所述是小編給大家介紹的java騰訊AI人臉對比對接詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
關(guān)于IDEA 2020.3 多窗口視圖丟失的問題
這篇文章主要介紹了關(guān)于IDEA 2020.3 多窗口視圖丟失的問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12
Spring源碼之事件監(jiān)聽機制詳解(@EventListener實現(xiàn)方式)
這篇文章主要介紹了Spring源碼之事件監(jiān)聽機制(@EventListener實現(xiàn)方式),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08
Spring中的@PropertySource注解源碼詳細(xì)解析
這篇文章主要介紹了Spring中的@PropertySource注解源碼詳細(xì)解析,@PropertySource注解,標(biāo)注在配置類@Configuration上面,下面主要分析一下@PropertySource注解的處理過程,也就是怎么把配置信息從.properies文件放到environment中的,需要的朋友可以參考下2024-01-01
SpringBoot后端接收參數(shù)優(yōu)化代碼示例(統(tǒng)一處理前端參數(shù))
使用Spring Boot開發(fā)API的時候,讀取請求參數(shù)是服務(wù)端編碼中最基本的一項操作,下面這篇文章主要給大家介紹了關(guān)于SpringBoot后端接收參數(shù)優(yōu)化(統(tǒng)一處理前端參數(shù))的相關(guān)資料,需要的朋友可以參考下2024-07-07
springboot2中HikariCP連接池的相關(guān)配置問題
這篇文章主要介紹了springboot2中HikariCP連接池的相關(guān)配置問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12

