亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java騰訊AI人臉對比對接代碼實例

發布時間:2020-08-25 14:56:51 來源:腳本之家 閱讀:249 作者:yjh44780791 欄目:編程語言

技術棧:

  1. Spring boot 2.x
  2. 騰訊
  3. java版本1.8

注意事項:

  1. 本文內的“**.**”需要自己替換為自己的路徑。
  2. 常量內的“**”需要自己定義自己內容。
  3. 業務中認證圖片,上傳至阿里云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、人臉識別業務: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;
 
 
/**
 * 人臉識別業務
 * @author: yanjianghua
 * @date: 2018/11/16 16:58
 */
 @Api(value = "人臉識別業務",description = "人臉識別業務")
 @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、邏輯實現類: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 {
 
  //編碼格式。發送編碼格式統一用UTF-8
  private static final String ENCODING = "UTF-8";
 
  //設置連接超時時間,單位毫秒。
  private static final int CONNECT_TIMEOUT = 6000;
 
  //請求獲取數據的超時時間(即響應時間),單位毫秒。
  private static final int SOCKET_TIMEOUT = 6000;
 
  /**
   * 發送get請求;不帶請求頭和請求參數
   *
   * @param url 請求地址
   * @return
   * @throws Exception
   */
  public static HttpClientResult doGet(String url) throws Exception {
    return doGet(url, null, null);
  }
 
  /**
   * 發送get請求;帶請求參數
   *
   * @param url 請求地址
   * @param params 請求參數集合
   * @return
   * @throws Exception
   */
  public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
    return doGet(url, null, params);
  }
 
  /**
   * 發送get請求;帶請求頭和請求參數
   *
   * @param url 請求地址
   * @param headers 請求頭集合
   * @param params 請求參數集合
   * @return
   * @throws Exception
   */
  public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
    // 創建httpClient對象
    CloseableHttpClient httpClient = HttpClients.createDefault();
 
    // 創建訪問的地址
    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());
      }
    }
 
    // 創建http對象
    HttpGet httpGet = new HttpGet(uriBuilder.build());
    /**
     * setConnectTimeout:設置連接超時時間,單位毫秒。
     * setConnectionRequestTimeout:設置從connect Manager(連接池)獲取Connection
     * 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連接池的。
     * setSocketTimeout:請求獲取數據的超時時間(即響應時間),單位毫秒。 如果訪問一個接口,多少時間內無法返回數據,就直接放棄此次調用。
     */
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
    httpGet.setConfig(requestConfig);
 
    // 設置請求頭
    packageHeader(headers, httpGet);
 
    // 創建httpResponse對象
    CloseableHttpResponse httpResponse = null;
 
    try {
      // 執行請求并獲得響應結果
      return getHttpClientResult(httpResponse, httpClient, httpGet);
    } finally {
      // 釋放資源
      release(httpResponse, httpClient);
    }
  }
 
  /**
   * 發送post請求;不帶請求頭和請求參數
   *
   * @param url 請求地址
   * @return
   * @throws Exception
   */
  public static HttpClientResult doPost(String url) throws Exception {
    return doPost(url, null, null);
  }
 
  /**
   * 發送post請求;帶請求參數
   *
   * @param url 請求地址
   * @param params 參數集合
   * @return
   * @throws Exception
   */
  public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
    return doPost(url, null, params);
  }
 
  /**
   * 發送post請求;帶請求頭和請求參數
   *
   * @param url 請求地址
   * @param headers 請求頭集合
   * @param params 請求參數集合
   * @return
   * @throws Exception
   */
  public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
    // 創建httpClient對象
    CloseableHttpClient httpClient = HttpClients.createDefault();
 
    // 創建http對象
    HttpPost httpPost = new HttpPost(url);
    /**
     * setConnectTimeout:設置連接超時時間,單位毫秒。
     * setConnectionRequestTimeout:設置從connect Manager(連接池)獲取Connection
     * 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連接池的。
     * setSocketTimeout:請求獲取數據的超時時間(即響應時間),單位毫秒。 如果訪問一個接口,多少時間內無法返回數據,就直接放棄此次調用。
     */
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
    httpPost.setConfig(requestConfig);
 
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
 
    // 設置請求頭
		/*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);
 
    // 封裝請求參數
    packageParam(params, httpPost);
 
    // 創建httpResponse對象
    CloseableHttpResponse httpResponse = null;
 
    try {
      // 執行請求并獲得響應結果
      return getHttpClientResult(httpResponse, httpClient, httpPost);
    } finally {
      // 釋放資源
      release(httpResponse, httpClient);
    }
  }
 
  /**
   * 發送put請求;不帶請求參數
   *
   * @param url 請求地址
   * @return
   * @throws Exception
   */
  public static HttpClientResult doPut(String url) throws Exception {
    return doPut(url);
  }
 
  /**
   * 發送put請求;帶請求參數
   *
   * @param url 請求地址
   * @param params 參數集合
   * @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);
    }
  }
 
  /**
   * 發送delete請求;不帶請求參數
   *
   * @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);
    }
  }
 
  /**
   * 發送delete請求;帶請求參數
   *
   * @param url 請求地址
   * @param params 參數集合
   * @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) {
        // 設置到請求頭到HttpRequestBase對象中
        httpMethod.setHeader(entry.getKey(), entry.getValue());
      }
    }
  }
 
  /**
   * Description: 封裝請求參數
   *
   * @param params
   * @param httpMethod
   * @throws UnsupportedEncodingException
   */
  public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
      throws UnsupportedEncodingException {
    // 封裝請求參數
    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()));
      }
 
      // 設置到請求的http對象中
      httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
    }
  }
 
  /**
   * Description: 獲得響應結果
   *
   * @param httpResponse
   * @param httpClient
   * @param httpMethod
   * @return
   * @throws Exception
   */
  public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
                            CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
    // 執行請求
    httpResponse = httpClient.execute(httpMethod);
 
    // 獲取返回結果
    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響應類

package com.**.**.result;
 
 
import java.io.Serializable;
 
/**
 * Description: 封裝httpClient響應結果
 * @author: yanjianghua
 * @date: 2018/9/12 13:45
 */
public class HttpClientResult implements Serializable {
 
  private static final long serialVersionUID = 2168152194164783950L;
 
  /**
   * 響應狀態碼
   */
  private int code;
 
  /**
   * 響應數據
   */
  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 {
 
  // 默認使用的redis的數據庫
  public static final Integer ASSETCENTER_DEFAULT_FLAG = 0;
 
  // redis的數據庫 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人臉對比對接詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

广宗县| 徐州市| 阿尔山市| 明光市| 原阳县| 阳信县| 开封市| 三河市| 通城县| 花莲市| 普兰店市| 道真| 慈溪市| 民丰县| 巴林左旗| 凤凰县| 镇雄县| 西贡区| 龙胜| 德清县| 呼和浩特市| 广水市| 东方市| 浦东新区| 霍山县| 三台县| 邹平县| 徐州市| 肥乡县| 大竹县| 南安市| 昌都县| 尤溪县| 巩留县| 博爱县| 廊坊市| 赤壁市| 阜城县| 台州市| 三台县| 阿荣旗|