java腾讯AI人脸对比对接代码实例

技术栈:

  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人脸对比对接详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

(0)

相关推荐

  • 详解java封装继承多态

    面向对象编程(Object Oriented Programming)有三大特性:封装.继承.多态.在这里,和大家一起加深对三者的理解. 封装 封装可以拆开理解,装,是把数据和方法放进了类里:封,把装进去的数据和成员方法加上访问权限.对于外界,内部细节是透明的,暴露给外面的是它的访问方法. 继承 继承,是为了重用父类代码.两个类若具有is a的关系就可以用extends.另外,继承也为实现多态做了铺垫. 多态 程序中定义的引用变量(java有两大数据类型,内部数据类型和引用数据类型)所指向的具体

  • Java代码实现随机生成汉字的方法

    一.背景知识 GB 2312-80 是中国国家标准简体中文字符集,全称<信息交换用汉字编码字符集·基本集>,由中国国家标准总局发布,1981年5月1日实施.GB2312 编码通行于中国大陆:新加坡等地也采用此编码.中国大陆几乎所有的中文系统和国际化的软件都支持 GB 2312. GB2312 标准共收录 6763 个汉字,其中一级汉字 3755 个,二级汉字 3008 个:同时收录了包括拉丁字母.希腊字母.日文平假名及片假名字母.俄语西里尔字母在内的 682 个字符.GB2312 的出现,基本

  • 使用Java SDK实现离线签名

    严格来说,tx-signer并不属于SDK,它是bytomd中构建交易.对交易签名两大模块的java实现版.因此,若想用tx-signer对交易进行离线签名,需要由你在本地保管好自己的私钥. 如果你的目的是完全脱离于bytomd全节点,可能需要自己做更多额外的工作.比如,在构建交易时,需要花费若干个utxo(Unspent Transaction Output)作为交易的输入,如果没有全节点则需要自身来维护utxo.当使用tx-signer构建完成一笔交易并签名后,若没有全节点的帮助,也需要自己

  • Java语言读取配置文件config.properties的方法讲解

    应用场景 有些时候项目中会用到很多路径,并且很可能多个路径在同一个根目录下,那为了方便配置的修改,达到只修改根目录即可达到一改全改的效果,此时就会想到要是有变量就好了: 另外有时候路径中的文件名是不确定的,要靠业务程序运行时去判断文件名应该如何设置,而又希望此文件下的目录名是确定的,那此时用变量也是比较好的解决方式. 一.配置文件config.properties是放在src根目录下的:例如我的是 /PropertiesTest/src/com/xuliugen/project/type.pro

  • Java算法之串的简单处理

    题目如下: 串的处理 在实际的开发工作中,对字符串的处理是最常见的编程任务. 本题目即是要求程序对用户输入的串进行处理.具体规则如下: 1. 把每个单词的首字母变为大写. 2. 把数字与字母之间用下划线字符(_)分开,使得更清晰 3. 把单词中间有多个空格的调整为1个空格. 例如: 用户输入: you and me what cpp2005program 则程序输出: You And Me What Cpp_2005_program 用户输入: this is a 99cat 则程序输出: Th

  • Java实现不同的类的属性之间相互赋值

    在开发的时候可能会出现将一个类的属性值,复制给另外一个类的属性值,这在读写数据库的时候,可能会经常的遇到 ,特别是对于一个有继承关系的类的时候,我们需要重写很多多余的代码,下面有一种简单的方法实现该功能 1.首先有两个类,两个类之间有相同的属性名和类型,也有不同的属性名很类型: public class ClassTestCopy2 { private int id; private String name; private String password; private String sex

  • Java中泛型总结(推荐)

    Java 泛型(generics)是 JDK 5 中引入的一个新特性, 泛型提供了编译时类型安全检测机制,该机制允许程序员在编译时检测到非法的类型. 泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数. 泛型类 范例:泛型类的基本语法 class MyClass<T> { T value1; } 尖括号 <> 中的 T 被称作是类型参数,用于指代任何类型.实际上这个T你可以任意写,但出于规范的目的,Java还是建议我们用单个大写字母来代表类型参数.常见的如: T 代表

  • java使用Base64实现文件加密解密

    本文实例为大家分享了Java实现Base64给文件加密.解密的具体代码,供大家参考,具体内容如下 package test.base64; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import sun.misc.BASE64Decoder;

  • 9种Java单例模式详解(推荐)

    单例模式的特点 一个类只允许产生一个实例化对象. 单例类构造方法私有化,不允许外部创建对象. 单例类向外提供静态方法,调用方法返回内部创建的实例化对象.  懒汉式(线程不安全) 其主要表现在单例类在外部需要创建实例化对象时再进行实例化,进而达到Lazy Loading 的效果. 通过静态方法 getSingleton() 和private 权限构造方法为创建一个实例化对象提供唯一的途径. 不足:未考虑到多线程的情况下可能会存在多个访问者同时访问,发生构造出多个对象的问题,所以在多线程下不可用这种

  • JavaScript刷新页面的几种方法总结

    1,reload 方法 该方法强迫浏览器刷新当前页面. 语法:location.reload([bForceGet]) 参数: bForceGet, 可选参数, 默认为 false,从客户端缓存里取当前页.true, 则以 GET 方式,从服务端取最新的页面, 相当于客户端点击 F5("刷新") 2,replace 方法 方法通过指定URL替换当前缓存在历史里(客户端)的项目,因此当使用replace方法之后,你不能通过"前进"和"后退"来访问已

随机推荐