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

本文介绍了一种基于HMAC-SHA1算法的鉴权签名方法,用于腾讯云OCR识别服务的安全调用。通过随机数、时间戳及密钥生成签名,确保API请求的完整性和安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

鉴权签名方法类:

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

}

 

 

#!/usr/local/bin/python3 # -- coding: utf-8 -- # @Time : 2023/6/11 14:19 # @Author : 志在星空 # @File : jietu12.py # @Software: PyCharm import base64 import urllib import requests import json API_KEY = "jHxdMDf2bhEPxcG6zFoRUejo" SECRET_KEY = "QF5GO9eLQncG2Zr1MKrxLOWvKAkAtVfI" def main(): # 发送 OCR 请求并获取响应 url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=" + get_access_token() # payload = 'image=%2F9j%2F4AAQ' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' } image_path = "11.jpg" with open(image_path, "rb") as image_file: image_data = image_file.read() response = requests.post(url, headers=headers, data=image_data) # response = requests.request("POST", url, headers=headers, data=payload) # 解析响应并提取 words_result 中的所有 words 字段 result = json.loads(response.text) print(result) # words_list = [item['words'] for item in result['words_result']] # print(words_list) # # # 打印所有提取到的内容 # for words in words_list: # print(words) def get_file_content_as_base64(path, urlencoded=False): """ 获取文件base64编码 :param path: 文件路径 :param urlencoded: 是否对结果进行urlencoded :return: base64编码信息 """ with open(path, "rb") as f: content = base64.b64encode(f.read()).decode("utf8") if urlencoded: content = urllib.parse.quote_plus(content) return content def get_access_token(): """ 使用 AK,SK 生成鉴权签名(Access Token) :return: access_token,或是None(如果错误) """ url = "https://aip.baidubce.com/oauth/2.0/token" params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY} return str(requests.post(url, params=params).json().get("access_token")) if name == 'main': main()运行出现{'log_id': 1667825949995168966, 'error_msg': 'param image not exist', 'error_code': 216101},请修改一下
06-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值