您的位置 首页 > 腾讯云社区

文字识别调用API(JAVA)---_12291_721

import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.io.*; import java.security.MessageDigest; import java.math.BigInteger; import java.text.SimpleDateFormat; import java.util.Base64; import java.util.Collections; import java.util.Date; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.net.URL; import java.net.URLConnection; import java.util.List; public class Demo { public static String imageToBase64Str(){ InputStream inputStream = null; byte[] data = null; try { inputStream = new FileInputStream("src\ceshi.png"); data = new byte[inputStream.available()]; inputStream.read(data); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } // 加密 Base64.Encoder encoder = Base64.getEncoder(); // BASE64Encoder encoder = new BASE64Encoder(); return encoder.encodeToString(data); } public static String sha256Hex(String s) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] d = md.digest(s.getBytes("UTF-8")); BigInteger no = new BigInteger(1, d); String hashtext = no.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } return hashtext; } 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 CanonicalRequest() throws Exception{ String HTTPRequestMethod = "POST"; String CanonicalURI = "/"; String CanonicalQueryString = ""; String CanonicalHeaders = "content-type:application/json; charset=utf-8nhost:ocr.tencentcloudapi.comn"; String SignedHeaders = "content-type;host"; //String Payload = "{"Limit": 1, "Filters": [{"Values": ["\u672a\u547d\u540d"], "Name": "instance-name"}]}"; String Payload = String.format("{"ImageBase64": "%s"}", imageToBase64Str()); String HashedRequestPayload = sha256Hex(Payload); return HTTPRequestMethod + 'n' + CanonicalURI + 'n' + CanonicalQueryString + 'n' + CanonicalHeaders + 'n' + SignedHeaders + 'n' + HashedRequestPayload; } public static String StringToSign() throws Exception{ String Algorithm = "TC3-HMAC-SHA256"; String RequestTimestamp = String.valueOf(System.currentTimeMillis() / 1000); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(System.currentTimeMillis()); String Timestamp = formatter.format(date); String CredentialScope = "2020-05-29"+"/ocr/tc3_request"; String HashedCanonicalRequest = sha256Hex(CanonicalRequest()); return Algorithm + 'n' + RequestTimestamp + 'n' + CredentialScope + 'n' + HashedCanonicalRequest; } public static String Signature() throws Exception{ String SecretKey = "SecretKey"; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(System.currentTimeMillis()); String Timestamp = formatter.format(date); byte[] secretDate = hmac256(("TC3" + SecretKey).getBytes("UTF8"), "2020-05-29"); byte[] secretService = hmac256(secretDate, "ocr"); byte[] secretSigning = hmac256(secretService, "tc3_request"); byte[] Signature = hmac256(secretSigning, StringToSign()); BigInteger no = new BigInteger(1, Signature); String hashtext = no.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } return "TC3-HMAC-SHA256" + ' '+ "Credential=" + "SecretID" + '/' + "2020-05-29/ocr/tc3_request" + ',' + "SignedHeaders=" + "content-type;host" + ',' + "Signature=" + hashtext; } public static void main(String[] args) throws Exception { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL("https://ocr.tencentcloudapi.com"); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("X-TC-Action", "GeneralBasicOCR"); conn.setRequestProperty("X-TC-Region", "ap-guangzhou"); String RequestTimestamp = String.valueOf(System.currentTimeMillis() / 1000); conn.setRequestProperty("X-TC-Timestamp", RequestTimestamp); conn.setRequestProperty("X-TC-Version", "2018-11-19"); conn.setRequestProperty("Authorization", Signature()); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setRequestProperty("Host", "ocr.tencentcloudapi.com"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(String.format("{"ImageBase64": "%s"}", imageToBase64Str())); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!"+e); e.printStackTrace(); } //使用finally块来关闭输出流、输入流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } System.out.println(result); } }

我也不知道为什么要这样写,反正可以跑通,不太会java

---来自腾讯云社区的---_12291_721

关于作者: 瞎采新闻

这里可以显示个人介绍!这里可以显示个人介绍!

热门文章

留言与评论(共有 0 条评论)
   
验证码: