java騰訊AI人臉對(duì)比對(duì)接代碼實(shí)例
技術(shù)棧:
- Spring boot 2.x
- 騰訊
- java版本1.8
注意事項(xiàng):
- 本文內(nèi)的“**.**”需要自己替換為自己的路徑。
- 常量?jī)?nèi)的“**”需要自己定義自己內(nèi)容。
- 業(yè)務(wù)中認(rèn)證圖片,上傳至阿里云OSS上
話不多說(shuō),直接上代碼
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、人臉識(shí)別業(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; /** * 人臉識(shí)別業(yè)務(wù) * @author: yanjianghua * @date: 2018/11/16 16:58 */ @Api(value = "人臉識(shí)別業(yè)務(wù)",description = "人臉識(shí)別業(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 = "人臉對(duì)比信息接口", notes = "人臉對(duì)比信息接口") @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 { /** * 人臉對(duì)比API接口 * @param imageBaseAuthentication * @param imageBase * @return */ public Object getFaceCompare(String imageBaseAuthentication, String imageBase); }
4、邏輯實(shí)現(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錯(cuò)誤") ; } 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è)置連接超時(shí)時(shí)間,單位毫秒。 private static final int CONNECT_TIMEOUT = 6000; //請(qǐng)求獲取數(shù)據(jù)的超時(shí)時(shí)間(即響應(yīng)時(shí)間),單位毫秒。 private static final int SOCKET_TIMEOUT = 6000; /** * 發(fā)送get請(qǐng)求;不帶請(qǐng)求頭和請(qǐng)求參數(shù) * * @param url 請(qǐng)求地址 * @return * @throws Exception */ public static HttpClientResult doGet(String url) throws Exception { return doGet(url, null, null); } /** * 發(fā)送get請(qǐng)求;帶請(qǐng)求參數(shù) * * @param url 請(qǐng)求地址 * @param params 請(qǐng)求參數(shù)集合 * @return * @throws Exception */ public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception { return doGet(url, null, params); } /** * 發(fā)送get請(qǐng)求;帶請(qǐng)求頭和請(qǐng)求參數(shù) * * @param url 請(qǐng)求地址 * @param headers 請(qǐng)求頭集合 * @param params 請(qǐng)求參數(shù)集合 * @return * @throws Exception */ public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception { // 創(chuàng)建httpClient對(duì)象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 創(chuàng)建訪問(wèn)的地址 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對(duì)象 HttpGet httpGet = new HttpGet(uriBuilder.build()); /** * setConnectTimeout:設(shè)置連接超時(shí)時(shí)間,單位毫秒。 * setConnectionRequestTimeout:設(shè)置從connect Manager(連接池)獲取Connection * 超時(shí)時(shí)間,單位毫秒。這個(gè)屬性是新加的屬性,因?yàn)槟壳鞍姹臼强梢怨蚕磉B接池的。 * setSocketTimeout:請(qǐng)求獲取數(shù)據(jù)的超時(shí)時(shí)間(即響應(yīng)時(shí)間),單位毫秒。 如果訪問(wèn)一個(gè)接口,多少時(shí)間內(nèi)無(wú)法返回?cái)?shù)據(jù),就直接放棄此次調(diào)用。 */ RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); httpGet.setConfig(requestConfig); // 設(shè)置請(qǐng)求頭 packageHeader(headers, httpGet); // 創(chuàng)建httpResponse對(duì)象 CloseableHttpResponse httpResponse = null; try { // 執(zhí)行請(qǐng)求并獲得響應(yīng)結(jié)果 return getHttpClientResult(httpResponse, httpClient, httpGet); } finally { // 釋放資源 release(httpResponse, httpClient); } } /** * 發(fā)送post請(qǐng)求;不帶請(qǐng)求頭和請(qǐng)求參數(shù) * * @param url 請(qǐng)求地址 * @return * @throws Exception */ public static HttpClientResult doPost(String url) throws Exception { return doPost(url, null, null); } /** * 發(fā)送post請(qǐng)求;帶請(qǐng)求參數(shù) * * @param url 請(qǐng)求地址 * @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請(qǐng)求;帶請(qǐng)求頭和請(qǐng)求參數(shù) * * @param url 請(qǐng)求地址 * @param headers 請(qǐng)求頭集合 * @param params 請(qǐng)求參數(shù)集合 * @return * @throws Exception */ public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception { // 創(chuàng)建httpClient對(duì)象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 創(chuàng)建http對(duì)象 HttpPost httpPost = new HttpPost(url); /** * setConnectTimeout:設(shè)置連接超時(shí)時(shí)間,單位毫秒。 * setConnectionRequestTimeout:設(shè)置從connect Manager(連接池)獲取Connection * 超時(shí)時(shí)間,單位毫秒。這個(gè)屬性是新加的屬性,因?yàn)槟壳鞍姹臼强梢怨蚕磉B接池的。 * setSocketTimeout:請(qǐng)求獲取數(shù)據(jù)的超時(shí)時(shí)間(即響應(yīng)時(shí)間),單位毫秒。 如果訪問(wèn)一個(gè)接口,多少時(shí)間內(nèi)無(wú)法返回?cá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è)置請(qǐng)求頭 /*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); // 封裝請(qǐng)求參數(shù) packageParam(params, httpPost); // 創(chuàng)建httpResponse對(duì)象 CloseableHttpResponse httpResponse = null; try { // 執(zhí)行請(qǐng)求并獲得響應(yīng)結(jié)果 return getHttpClientResult(httpResponse, httpClient, httpPost); } finally { // 釋放資源 release(httpResponse, httpClient); } } /** * 發(fā)送put請(qǐng)求;不帶請(qǐng)求參數(shù) * * @param url 請(qǐng)求地址 * @return * @throws Exception */ public static HttpClientResult doPut(String url) throws Exception { return doPut(url); } /** * 發(fā)送put請(qǐng)求;帶請(qǐng)求參數(shù) * * @param url 請(qǐng)求地址 * @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請(qǐng)求;不帶請(qǐng)求參數(shù) * * @param url 請(qǐng)求地址 * @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請(qǐng)求;帶請(qǐng)求參數(shù) * * @param url 請(qǐng)求地址 * @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: 封裝請(qǐng)求頭 * @param params * @param httpMethod */ public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) { // 封裝請(qǐng)求頭 if (params != null) { Set<Entry<String, String>> entrySet = params.entrySet(); for (Entry<String, String> entry : entrySet) { // 設(shè)置到請(qǐng)求頭到HttpRequestBase對(duì)象中 httpMethod.setHeader(entry.getKey(), entry.getValue()); } } } /** * Description: 封裝請(qǐng)求參數(shù) * * @param params * @param httpMethod * @throws UnsupportedEncodingException */ public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod) throws UnsupportedEncodingException { // 封裝請(qǐng)求參數(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è)置到請(qǐng)求的http對(duì)象中 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í)行請(qǐng)求 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ù)庫(kù) public static final Integer ASSETCENTER_DEFAULT_FLAG = 0; // redis的數(shù)據(jù)庫(kù) 1庫(kù) public static final Integer ASSETCENTER_BUSNESS_FLAG = 1; /** * 騰訊AI對(duì)外開(kāi)放平臺(tái)-APP_ID */ public static final int APP_ID_AI_OCR = *********; /** * 騰訊AI對(duì)外開(kāi)放平臺(tái)-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人臉對(duì)比對(duì)接詳解整合,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
Java8新特性O(shè)ptional類及新時(shí)間日期API示例詳解
這篇文章主要為大家介紹了Java8新特性O(shè)ptional類及新時(shí)間日期API示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11servlet生命周期_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要為大家詳細(xì)介紹了servlet生命周期的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07Java中的synchronized和ReentrantLock的區(qū)別詳細(xì)解讀
這篇文章主要介紹了Java中的synchronized和ReentrantLock的區(qū)別詳細(xì)解讀,synchronized是Java內(nèi)建的同步機(jī)制,所以也有人稱其為 IntrinsicLocking,它提供了互斥的語(yǔ)義和可見(jiàn)性,當(dāng)一個(gè)線程已經(jīng)獲取當(dāng)前鎖時(shí),其他試圖獲取的線程只能等待或者阻塞在那里,需要的朋友可以參考下2024-01-01Java基礎(chǔ) Servlet監(jiān)聽(tīng)器詳解
這篇文章主要介紹了Java基礎(chǔ) Servlet監(jiān)聽(tīng)器詳解的相關(guān)資料,需要的朋友可以參考下2017-07-07使用Thrift實(shí)現(xiàn)跨語(yǔ)言RPC的調(diào)用
Thrift最大的優(yōu)勢(shì)就是可以實(shí)現(xiàn)跨語(yǔ)言RPC調(diào)用,尤其在一些大廠,微服務(wù)各模塊之間使用不同的語(yǔ)言是很常見(jiàn)的,本文就將使用java作為服務(wù)端,用python作為客戶端,實(shí)現(xiàn)不同語(yǔ)言之間的RPC調(diào)用,需要的可以參考下2023-10-10mybatis攔截器實(shí)現(xiàn)數(shù)據(jù)權(quán)限項(xiàng)目實(shí)踐
本文主要介紹了mybatis攔截器實(shí)現(xiàn)數(shù)據(jù)權(quán)限項(xiàng)目實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06