腾讯OCR接口遇到的坑

最初用腾讯提供的代码编写的OCR 总是报签名异常,后来经过读源码总结出一套可用的http请求,期望给入坑的小伙伴们带来帮助

 

package com.stylefeng.guns.modular.applet.util.idcardutils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class TencentCloudAPITC3Demo {
    private final static Charset UTF8 = StandardCharsets.UTF_8;
    private final static String SECRET_ID = "AKID093hMVd1WJsCF2KQ2NZ??????????";
    private final static String SECRET_KEY = "feMxgBD1auxkH0SeZEcq?????????";
    private final static String CT_JSON = "application/json; charset=utf-8";

    public static byte[] hmac256(byte[] key, String msg) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());
        mac.init(secretKeySpec);
        return mac.doFinal(msg.getBytes(UTF8));
    }

    public static String sha256Hex(String s) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] d = md.digest(s.getBytes(UTF8));
        return DatatypeConverter.printHexBinary(d).toLowerCase();
    }

    public static void main(String[] args) throws Exception {
        String service = "ocr";
        String host = "ocr.tencentcloudapi.com";
        String region = "ap-beijing";
        String action = "IDCardOCR";
        String version = "2018-11-19";
        String algorithm = "TC3-HMAC-SHA256";
        //String timestamp = "1551113065";
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        String date = sdf.format(new Date(Long.valueOf(timestamp + "000")));

        String httpRequestMethod = "POST";
        String canonicalUri = "/";
        String canonicalQueryString = "";
        String canonicalHeaders = "content-type:application/json; charset=utf-8\n" + "host:" + host + "\n";
        String signedHeaders = "content-type;host";
        JSONObject json = new JSONObject();
        json.put("ImageBase64","你的base64图片");
        json.put("CardSide","FRONT");
        JSONObject configJson = new JSONObject();
        configJson.put("CropIdCard",true);
        json.put("Config",JSONObject.toJSONString(configJson));
        String payload = JSONObject.toJSONString(json);
        String hashedRequestPayload = sha256Hex(payload);
        String canonicalRequest = httpRequestMethod + "\n" + canonicalUri + "\n" + canonicalQueryString + "\n"
                + canonicalHeaders + "\n" + signedHeaders + "\n" + hashedRequestPayload;
        //System.out.println(canonicalRequest);

        String credentialScope = date + "/" + service + "/" + "tc3_request";
        String hashedCanonicalRequest = sha256Hex(canonicalRequest);
        String stringToSign = algorithm + "\n" + timestamp + "\n" + credentialScope + "\n" + hashedCanonicalRequest;
        //System.out.println(stringToSign);

        byte[] secretDate = hmac256(("TC3" + SECRET_KEY).getBytes(UTF8), date);
        byte[] secretService = hmac256(secretDate, service);
        byte[] secretSigning = hmac256(secretService, "tc3_request");
        String signature = DatatypeConverter.printHexBinary(hmac256(secretSigning, stringToSign)).toLowerCase();
        //System.out.println(signature);

        String authorization = algorithm + " " + "Credential=" + SECRET_ID + "/" + credentialScope + ", "
                + "SignedHeaders=" + signedHeaders + ", " + "Signature=" + signature;
        //System.out.println(authorization);

        TreeMap headers = new TreeMap();
        headers.put("Authorization", authorization);
        headers.put("Content-Type", CT_JSON);
        headers.put("Host", host);
        headers.put("X-TC-Action", action);
        headers.put("X-TC-Timestamp", timestamp);
        headers.put("X-TC-Version", version);
        headers.put("X-TC-Region", region);


        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost( "https://"+host );// 鍒涘缓httpPost
        httpPost.setHeader( "Authorization", authorization);
        httpPost.setHeader( "Content-Type", "application/json; charset=utf-8");
        httpPost.setHeader( "Host", host);
        httpPost.setHeader( "X-TC-Action", action);
        httpPost.setHeader( "X-TC-Timestamp", timestamp);
        httpPost.setHeader( "X-TC-Version", version);
        httpPost.setHeader( "X-TC-Region", region);
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity( payload, charSet );
        httpPost.setEntity( entity );
        CloseableHttpResponse response = null;


        response = httpclient.execute( httpPost );
        StatusLine status = response.getStatusLine();
        int state = status.getStatusCode();
        HttpEntity responseEntity = response.getEntity();
        String jsonString = EntityUtils.toString( responseEntity );
        System.out.println(jsonString);
    }
}

你可能感兴趣的:(后端,人工智能,机器学习,前端)