腾讯云OCR身份证识别 multipart/form-data和application/json 格式方法实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zwl18210851801/article/details/85618028

鉴权签名方法类:

package com.x.common.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Random;

/**
 * 腾讯云ocr识别鉴权签名类
 */
public class OcrCardSign {
    /**
     * 生成 Authorization 签名字段
     *
     * @param appId
     * @param secretId
     * @param secretKey
     * @param bucketName
     * @param expired
     * @return
     * @throws Exception
     */
    public static String appSign(long appId, String secretId, String secretKey, String bucketName,
                                 long expired) throws Exception {
        long now = System.currentTimeMillis() / 1000;
        int rdm = Math.abs(new Random().nextInt());
        String plainText = String.format("a=%d&b=%s&k=%s&t=%d&e=%d&r=%d", appId, bucketName,
                secretId, now, now + expired, rdm);
        byte[] hmacDigest = HmacSha1(plainText, secretKey);
        byte[] signContent = new byte[hmacDigest.length + plainText.getBytes().length];
        System.arraycopy(hmacDigest, 0, signContent, 0, hmacDigest.length);
        System.arraycopy(plainText.getBytes(), 0, signContent, hmacDigest.length,
                plainText.getBytes().length);
        return Base64Encode(signContent);
    }

    /**
     * 生成 base64 编码
     *
     * @param binaryData
     * @return
     */
    public static String Base64Encode(byte[] binaryData) {
        String encodedstr = Base64.getEncoder().encodeToString(binaryData);
        return encodedstr;
    }

    /**
     * 生成 hmacsha1 签名
     *
     * @param binaryData
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] HmacSha1(byte[] binaryData, String key) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        mac.init(secretKey);
        byte[] HmacSha1Digest = mac.doFinal(binaryData);
        return HmacSha1Digest;
    }

    /**
     * 生成 hmacsha1 签名
     *
     * @param plainText
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] HmacSha1(String plainText, String key) throws Exception {
        return HmacSha1(plainText.getBytes(), key);
    }

}

方法实现类:

package com.x.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import java.util.HashMap;
import java.util.Map;
import static com.x.common.utils.HttpConnection.doPostByForm;

public class OcrUtilTest {

  @Value("${app.appId}")
  private long appId;
  @Value("${app.secretId}")
  private String secretId;
  @Value("${app.secretKey}")
  private String secretKey;

  /**
   *  获取鉴权签名
   */
  public static String sign()throws Exception {
    String sign= OcrCardSign.appSign(123456789,"AKID3uRss1lwsbdagaE11zMysQswvMR9l","oY9ZsEd7g7adfgvafgaKZnUiTNFLvWev",null,123456);
    //String sign= OcrCardSign.appSign(appId,secretId,secretKey,null,123456);
    System.out.print(sign);
    return sign;
  }

  /**
   * 通过线上图片url获取信息
   * @throws Exception
   */
  public static void getInfoByUrl() throws Exception{
    String sign=sign();
    String url="https://recognition.image.myqcloud.com/ocr/idcard";
    JSONObject obj=new JSONObject();
    obj.put("appid","123456789");
    obj.put("card_type",0);
    obj.put("url_list",new String[]{"https://xxx.com/file/img/a.jpg"});
    String str=HttpConnection.doPostBySign(url,obj.toJSONString(),sign);
    System.out.print(str);
  }

  /**
   * 通过上传图片获取信息
   * @throws Exception
   */
  public static void getInfoByForm() throws Exception{
    String url = "https://recognition.image.myqcloud.com/ocr/idcard";
    String fileUrl = "https://xxx.com/file/img/a.jpg";
    Map<String, String> textMap = new HashMap<>();
    //可以设置多个参数
    textMap.put("appid","123456789");
    textMap.put("card_type","0");
    //设置file的Url路径
    Map<String, String> fileMap = new HashMap<>();
    fileMap.put("image[0]", fileUrl);
    String ret = doPostByForm(url,textMap,fileMap,sign());
    System.out.println(ret);
  }


  public static void main(String[] args) throws Exception{
    String url = "https://recognition.image.myqcloud.com/ocr/idcard";
    String fileUrl = "https://xxx.com/file/img/a.jpg";
    Map<String, String> textMap = new HashMap<>();
    //可以设置多个参数
    textMap.put("appid","123456789");
    textMap.put("card_type","0");
    //设置file的Url路径
    Map<String, String> fileMap = new HashMap<>();
    fileMap.put("image[0]", fileUrl);
    String ret = doPostByForm(url,textMap,fileMap,sign());
    System.out.println(ret);
  }

}

Http连接公共类:

package com.x.common.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

public class HttpConnection {
  public static String doGet (String httpurl) {
    HttpURLConnection connection = null;
    InputStream is = null;
    BufferedReader br = null;
    String result = null;// 返回结果字符串
    try {
      // 创建远程url连接对象
      URL url = new URL(httpurl);
      // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
      connection = (HttpURLConnection) url.openConnection();
      // 设置连接方式:get
      connection.setRequestMethod("GET");
      // 设置连接主机服务器的超时时间:15000毫秒
      connection.setConnectTimeout(5000);
      // 设置读取远程返回的数据时间:60000毫秒
      connection.setReadTimeout(10000);
      // 发送请求
      connection.connect();
      // 通过connection连接,获取输入流
      if (connection.getResponseCode() == 200) {
        is = connection.getInputStream();
        // 封装输入流is,并指定字符集
        br = new BufferedReader(new InputStreamReader(is, "utf-8"));
        // 存放数据
        StringBuffer sbf = new StringBuffer();
        String temp = null;
        while ((temp = br.readLine()) != null) {
          sbf.append(temp);
          sbf.append("\r\n");
        }
        result = sbf.toString();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 关闭资源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      connection.disconnect();// 关闭远程连接
    }

    return result;
  }

  public static String doPost (String httpUrl, String param) {

    HttpURLConnection connection = null;
    InputStream is = null;
    OutputStream os = null;
    BufferedReader br = null;
    String result = null;
    try {
      URL url = new URL(httpUrl);
      // 通过远程url连接对象打开连接
      connection = (HttpURLConnection) url.openConnection();
      // 设置连接请求方式
      connection.setRequestMethod("POST");
      // 设置连接主机服务器超时时间:15000毫秒
      connection.setConnectTimeout(5000);
      // 设置读取主机服务器返回数据超时时间:60000毫秒
      connection.setReadTimeout(15000);

      // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
      connection.setDoOutput(true);
      // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
      connection.setDoInput(true);
      // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
      connection.setRequestProperty("Content-Type",
        "application/x-www-form-urlencoded");
      // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
      connection.setRequestProperty("Authorization",
        "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
      // 通过连接对象获取一个输出流
      os = connection.getOutputStream();
      // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
      os.write(param.getBytes());
      // 通过连接对象获取一个输入流,向远程读取
      if (connection.getResponseCode() == 200) {

        is = connection.getInputStream();
        // 对输入流对象进行包装:charset根据工作项目组的要求来设置
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        StringBuffer sbf = new StringBuffer();
        String temp = null;
        // 循环遍历一行一行读取数据
        while ((temp = br.readLine()) != null) {
          sbf.append(temp);
          sbf.append("\r\n");
        }
        result = sbf.toString();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 关闭资源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != os) {
        try {
          os.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 断开与远程地址url的连接
      connection.disconnect();
    }
    return result;
  }

  

  public static String doPostBySign (
    String httpUrl, String param, String sign) {

    HttpURLConnection connection = null;
    InputStream is = null;
    OutputStream os = null;
    BufferedReader br = null;
    String result = null;
    try {
      URL url = new URL(httpUrl);
      // 通过远程url连接对象打开连接
      connection = (HttpURLConnection) url.openConnection();
      // 设置连接请求方式
      connection.setRequestMethod("POST");
      // 设置连接主机服务器超时时间:15000毫秒
      connection.setConnectTimeout(5000);
      // 设置读取主机服务器返回数据超时时间:60000毫秒
      connection.setReadTimeout(15000);

      // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
      connection.setDoOutput(true);
      // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
      connection.setDoInput(true);
      // 设置传入参数的格式:请求参数应该是 json字符串格式。
      connection.setRequestProperty("Content-Type", "application/json");
      // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
      connection.setRequestProperty("Authorization", sign);
      // 通过连接对象获取一个输出流
      os = connection.getOutputStream();
      // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
      os.write(param.getBytes());
      // 通过连接对象获取一个输入流,向远程读取
      if (connection.getResponseCode() == 200) {

        is = connection.getInputStream();
        // 对输入流对象进行包装:charset根据工作项目组的要求来设置
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        StringBuffer sbf = new StringBuffer();
        String temp = null;
        // 循环遍历一行一行读取数据
        while ((temp = br.readLine()) != null) {
          sbf.append(temp);
          sbf.append("\r\n");
        }
        result = sbf.toString();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 关闭资源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != os) {
        try {
          os.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 断开与远程地址url的连接
      connection.disconnect();
    }
    return result;
  }

  public static String doPostByForm (String urlStr, Map<String, String> textMap, Map<String, String> fileMap,String sign) {
    String res = "";
    HttpURLConnection conn = null;
    // boundary就是request头和上传文件内容的分隔符
    String BOUNDARY = "---------------------------123821742118716";
    try {
      URL url = new URL(urlStr);
      conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(5000);
      conn.setReadTimeout(30000);
      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.setUseCaches(false);
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
      //设置鉴权信息
      conn.setRequestProperty("Authorization", sign);
      OutputStream out = new DataOutputStream(conn.getOutputStream());
      // text
      if (textMap != null) {
        StringBuffer strBuf = new StringBuffer();
        Iterator iter = textMap.entrySet().iterator();
        while (iter.hasNext()) {
          Map.Entry entry = (Map.Entry) iter.next();
          String inputName = (String) entry.getKey();
          String inputValue = (String) entry.getValue();
          if (inputValue == null) {
            continue;
          }
          strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
          strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
          strBuf.append(inputValue);
        }
        out.write(strBuf.toString().getBytes());
      }
      // file
      if (fileMap != null) {
        Iterator iter = fileMap.entrySet().iterator();
        while (iter.hasNext()) {
          Map.Entry entry = (Map.Entry) iter.next();
          String inputName = (String) entry.getKey();
          String inputValue = (String) entry.getValue();
          if (inputValue == null) {
            continue;
          }
          String filename = inputValue.substring(inputValue.lastIndexOf("/")+1,inputValue.length());
          //文件类型,默认采用application/octet-stream
          String contentType = "application/octet-stream";
          if (filename.endsWith(".png")) {
            contentType = "image/png";
          } else if (filename.endsWith(".jpg") ||
            filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
            contentType = "image/jpeg";
          } else if (filename.endsWith(".gif")) {
            contentType = "image/gif";
          } else if (filename.endsWith(".ico")) {
            contentType = "image/image/x-icon";
          }
          StringBuffer strBuf = new StringBuffer();
          strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
          strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
          strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
          out.write(strBuf.toString().getBytes());
          URL fileUrl = new URL(inputValue);
          URLConnection fileConn = fileUrl.openConnection();
          InputStream in2 = fileConn.getInputStream();
          DataInputStream in = new DataInputStream(in2);
          int bytes = 0;
          byte[] bufferOut = new byte[1024];
          while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
          }
          in.close();
        }
      }
      byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
      out.write(endData);
      out.flush();
      out.close();
      // 读取返回数据
      StringBuffer strBuf = new StringBuffer();
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line = null;
      while ((line = reader.readLine()) != null) {
        strBuf.append(line).append("\n");
      }
      res = strBuf.toString();
      reader.close();
      reader = null;
    } catch (Exception e) {
      System.out.println("发送POST请求出错");
      e.printStackTrace();
    } finally {
      if (conn != null) {
        conn.disconnect();
        conn = null;
      }
    }
    return res;
  }

}

猜你喜欢

转载自blog.csdn.net/zwl18210851801/article/details/85618028