探索机械臂轨迹规划:鲸鱼算法优化353多项式的奇妙旅程
2025/12/17 23:01:23
小白也能跑通华为云OCR:手把手整合 Hutool 与华为云签名 SDK 并解决依赖难题
如果你喜欢我的回答或想获取更多有趣、有用的内容,
欢迎关注微信公众号:云技纵横 ,
这样就能及时看到我的更新啦~ 😊 你的支持是我前进的动力!
一、两种调用方式总览
二、方式A 官方通用 SDK 完整示例(推荐)
<dependencies><!-- 华为云 OCR SDK --><dependency><groupId>com.huaweicloud</groupId><artifactId>huaweicloud-sdk-ocr</artifactId><version>3.1.12</version></dependency><!-- JSON 工具(可选) --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-json</artifactId><version>5.8.22</version></dependency></dependencies>publicclassBase64Util{publicstaticStringimageToBase64(StringimgPath)throwsException{byte[]bytes=Files.readAllBytes(Paths.get(imgPath));returnBase64.getEncoder().encodeToString(bytes);}}publicclassOcrOfficialSdkDemo{// 建议通过环境变量读取:HUAWEICLOUD_SDK_AK / HUAWEICLOUD_SDK_SKprivatestaticfinalStringAK=System.getenv("HUAWEICLOUD_SDK_AK");privatestaticfinalStringSK=System.getenv("HUAWEICLOUD_SDK_SK");// 区域:如 cn-north-4;也可改为 endpoint 方式privatestaticfinalStringREGION="cn-north-4";publicstaticvoidmain(String[]args){try{// 1) 读取图片 Base64StringimgBase64=Base64Util.imageToBase64("D:/tmp/demo.png");// 2) 认证与客户端BasicCredentialscred=newBasicCredentials().withAk(AK).withSk(SK);// 如使用永久 AK/SK,部分场景需填写 projectId(按控制台指引获取)// cred.withProjectId("your-project-id");HttpConfigconfig=HttpConfig.getDefaultHttpConfig().withTimeout(60);// 可按需调整OcrClientclient=OcrClient.newBuilder().withHttpConfig(config).withCredential(cred).withRegion(OcrRegion.valueOf(REGION)).build();// 3) 组装请求(以表格识别为例,支持图片URL或Base64)RecognizeGeneralTableRequestreq=newRecognizeGeneralTableRequest();GeneralTableRequestBodybody=newGeneralTableRequestBody()// .withUrl("https://your-obs-url/xxx.png") // 也可传 URL.withImageBase64(imgBase64);req.withBody(body);// 4) 发送请求RecognizeGeneralTableResponseresp=client.recognizeGeneralTable(req);System.out.println("OCR 调用成功:\n"+resp.toString());// 5) 业务字段抽取示例(按实际接口返回结构调整)// 通用表格接口返回结构不同,请参考控制台 API 文档解析// Map<String, Object> result = resp.getResult();// String tableStr = JSONUtil.toJsonStr(result);// System.out.println("抽取结果:\n" + tableStr);}catch(ConnectionException|RequestTimeoutExceptione){System.err.println("网络类异常:"+e.getMessage());}catch(ServiceResponseExceptione){System.err.println("服务响应异常:");System.err.println("HTTP状态码="+e.getHttpStatusCode());System.err.println("错误码="+e.getErrorCode());System.err.println("错误信息="+e.getErrorMsg());}}}三、方式B 签名 SDK + Hutool 完整示例(当前写法,含依赖安装脚本)
# 将 java-sdk-core-3.2.4.jar 放到当前目录后执行mvn install:install-file\-Dfile=java-sdk-core-3.2.4.jar\-DgroupId=com.huaweicloud.apigateway\-DartifactId=java-sdk-core\-Dversion=3.2.4\-Dpackaging=jar<dependencies><!-- Hutool 工具 --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.22</version></dependency><!-- Apache HttpClient --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.14</version></dependency><!-- 华为云网关签名 SDK(已本地安装或私有仓库托管) --><dependency><groupId>com.huaweicloud.apigateway</groupId><artifactId>java-sdk-core</artifactId><version>3.2.4</version></dependency></dependencies>publicclassHuaweiCloudOcr{publicHashMap<String,String>identifyWaybill(StringimgBase64)throwsException{Requestrequest=newRequest();request.setKey(appKey);request.setSecret(appSecret);request.setMethod("POST");request.setUrl("https://jmexpressbill.apistore.huaweicloud.com/ocr/express-bill");request.addHeader("Content-Type","application/x-www-form-urlencoded");Stringencode=URLUtil.encodeAll(imgBase64);request.setBody("base64="+encode);HttpRequestBasesignedRequest=Client.sign(request);// 发送请求try(CloseableHttpClientclient=HttpClients.createDefault();CloseableHttpResponseresp=client.execute(signedRequest)){intstatus=resp.getStatusLine().getStatusCode();if(status!=200){Stringbody=resp.getEntity()==null?"":EntityUtils.toString(resp.getEntity(),"UTF-8");log.error("OCR识别失败,HTTP状态码={},响应={}",status,body);thrownewRuntimeException("OCR识别运单失败,HTTP "+status);}HttpEntityentity=resp.getEntity();if(entity==null)thrownewRuntimeException("OCR响应体为空");StringrespStr=EntityUtils.toString(entity,"UTF-8");JSONObjectjson=JSONUtil.parseObj(respStr);intcode=json.getInt("code",-1);Stringmsg=json.getStr("msg","未知错误");}}}四、常见问题与排查清单