评论

收藏

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

编程语言 编程语言 发布于:2021-09-17 22:27 | 阅读数:433 | 评论:0

这篇文章主要介绍了java腾讯AI人脸对比对接,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
技术栈:

  • spring boot 2.x
  • 腾讯
  • java版本1.8
注意事项:

  • 本文内的“**.**”需要自己替换为自己的路径。
  • 常量内的“**”需要自己定义自己内容。
  • 业务中认证图片,上传至阿里云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人脸对比对接详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对CodeAE代码之家网站的支持!
原文链接:https://blog.csdn.net/yjh44780791/article/details/84652282
关注下面的标签,发现更多相似文章