栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

技术栈:

  1. Spring boot 2.x
  2. 腾讯
  3. java版本1.8

注意事项:

  1. 本文内的“**.**”需要自己替换为自己的路径。
  2. 常量内的“**”需要自己定义自己内容。
  3. 业务中认证图片,上传至阿里云OSS上

话不多说,直接上代码

1、pom文件:


		
			org.apache.httpcomponents
			httpclient
			4.5.6
		
 
 
		
		
			com.aliyun.oss
			aliyun-sdk-oss
			2.2.1
		

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;
 
 

 @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;
 

public interface IFaceService {
 
  
  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;
 

@Service
public class IFaceServiceImpl implements IFaceService {
 
  @Override
  public Object getFaceCompare(String imagebaseAuthentication, String imagebase){
    HttpClientResult result = null;
 
    Map params = new HashMap();
    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;
 

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;
 
  
  public static HttpClientResult doGet(String url) throws Exception {
    return doGet(url, null, null);
  }
 
  
  public static HttpClientResult doGet(String url, Map params) throws Exception {
    return doGet(url, null, params);
  }
 
  
  public static HttpClientResult doGet(String url, Map headers, Map params) throws Exception {
    // 创建httpClient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
 
    // 创建访问的地址
    URIBuilder uriBuilder = new URIBuilder(url);
    if (params != null) {
      Set> entrySet = params.entrySet();
      for (Entry entry : entrySet) {
 uriBuilder.setParameter(entry.getKey(), entry.getValue());
      }
    }
 
    // 创建http对象
    HttpGet httpGet = new HttpGet(uriBuilder.build());
    
    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);
    }
  }
 
  
  public static HttpClientResult doPost(String url) throws Exception {
    return doPost(url, null, null);
  }
 
  
  public static HttpClientResult doPost(String url, Map params) throws Exception {
    return doPost(url, null, params);
  }
 
  
  public static HttpClientResult doPost(String url, Map headers, Map params) throws Exception {
    // 创建httpClient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
 
    // 创建http对象
    HttpPost httpPost = new HttpPost(url);
    
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
    httpPost.setConfig(requestConfig);
 
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
 
    // 设置请求头
		
    packageHeader(headers, httpPost);
 
    // 封装请求参数
    packageParam(params, httpPost);
 
    // 创建httpResponse对象
    CloseableHttpResponse httpResponse = null;
 
    try {
      // 执行请求并获得响应结果
      return getHttpClientResult(httpResponse, httpClient, httpPost);
    } finally {
      // 释放资源
      release(httpResponse, httpClient);
    }
  }
 
  
  public static HttpClientResult doPut(String url) throws Exception {
    return doPut(url);
  }
 
  
  public static HttpClientResult doPut(String url, Map 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);
    }
  }
 
  
  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);
    }
  }
 
  
  public static HttpClientResult doDelete(String url, Map params) throws Exception {
    if (params == null) {
      params = new HashMap();
    }
 
    params.put("_method", "delete");
    return doPost(url, params);
  }
 
  
  public static void packageHeader(Map params, HttpRequestbase httpMethod) {
    // 封装请求头
    if (params != null) {
      Set> entrySet = params.entrySet();
      for (Entry entry : entrySet) {
 // 设置到请求头到HttpRequestbase对象中
 httpMethod.setHeader(entry.getKey(), entry.getValue());
      }
    }
  }
 
  
  public static void packageParam(Map params, HttpEntityEnclosingRequestbase httpMethod)
      throws UnsupportedEncodingException {
    // 封装请求参数
    if (params != null) {
      List nvps = new ArrayList();
      Set> entrySet = params.entrySet();
      for (Entry entry : entrySet) {
 nvps.add(new BasicNamevaluePair(entry.getKey(), entry.getValue()));
      }
 
      // 设置到请求的http对象中
      httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
    }
  }
 
  
  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);
  }
 
  
  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;
 

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/138617.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号