add:ocr请求替换为okhttp

This commit is contained in:
2510220824
2021-08-24 13:30:39 +08:00
parent a242b9ac56
commit bf8a247cf2
4 changed files with 290 additions and 17 deletions
+5
View File
@@ -99,6 +99,11 @@
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
</dependencies>
<build>
@@ -0,0 +1,69 @@
package com.adc.da.ocr.config;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
@Configuration
public class OkHttpConfig {
@Bean
public X509TrustManager x509TrustManager() {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
}
@Bean
public SSLSocketFactory sslSocketFactory() {
try {
//信任任何链接
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}
/**
* Create a new connection pool with tuning parameters appropriate for a single-user application.
* The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
*/
@Bean
public ConnectionPool pool() {
return new ConnectionPool(200, 5, TimeUnit.MINUTES);
}
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory(), x509TrustManager())
.retryOnConnectionFailure(false)//是否开启缓存
.connectionPool(pool())//连接池
.connectTimeout(10L, TimeUnit.SECONDS)
.readTimeout(10L, TimeUnit.SECONDS)
.build();
}
}
@@ -7,6 +7,7 @@ import com.adc.da.ocr.entity.OcrRecordEO;
import com.adc.da.ocr.entity.OcrResultEo;
import com.adc.da.ocr.service.OCRRestfulService;
import com.adc.da.ocr.util.Base64Util;
import com.adc.da.ocr.util.OkHttpUtil;
import com.adc.da.ocr.util.RsaUtil;
import com.adc.da.ocr.util.UUIDUtils;
import com.alibaba.fastjson.JSONObject;
@@ -15,6 +16,7 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
@@ -32,6 +34,8 @@ import com.adc.da.sys.util.LoginUserUtil;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
@Transactional(value = "transactionManager", readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
@@ -53,8 +57,11 @@ public class OCRRestfulServiceImpl implements OCRRestfulService {
@Value("${OCR.convertType}")
private String convertType;
@Autowired
@Qualifier(value = "remoteRestTemplate")
private RestTemplate restTemplate;
@Autowired
private OkHttpUtil okHttpUtil;
@Autowired
private OcrRecordEODao ocrRecordEODao;
//ocr处理文件后存放url
@Value("${OCR.ocrPath}")
@@ -81,28 +88,27 @@ public class OCRRestfulServiceImpl implements OCRRestfulService {
logger.error("PDF转Base64失败");
return Result.error("PDF转Base64失败");
}
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add("userId",OcrUserId);
paramMap.add("authCode",authCode);
paramMap.add("convertType",convertType);
paramMap.add("fileName",fileName);
paramMap.add("fileContent",fileContent);
paramMap.add("taskId",taskId);
paramMap.add("callBackUrl",RestCallBackUrl);
paramMap.add("callBackMethod","");
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
logger.info("处理完文件数据,开始请求OCR接口数据:【"+sdf.format(new Date())+"");
try{
ResponseEntity<String> responseEntity = restTemplate.postForEntity(RestHandleFileUrl, httpEntity, String.class);
//ResponseEntity<String> responseEntity = restTemplate.postForEntity(RestHandleFileUrl, httpEntity, String.class);
Map<String,String> map = new HashMap<>();
map.put("userId",OcrUserId);
map.put("authCode",authCode);
map.put("convertType",convertType);
map.put("fileName",fileName);
map.put("fileContent",fileContent);
map.put("taskId",taskId);
map.put("callBackUrl",RestCallBackUrl);
map.put("callBackMethod","");
logger.info("处理完文件数据,开始请求OCR接口数据:【"+sdf.format(new Date())+"");
String result = okHttpUtil.post(RestHandleFileUrl,map,new HashMap<>());
logger.info("okHttp结果:"+result);
logger.info("请求OCR接口完毕,返回响应状态:【"+sdf.format(new Date())+"");
HttpStatus statusCode = responseEntity.getStatusCode();
if(statusCode != HttpStatus.OK){
logger.error("请求出现异常:"+statusCode.value());
if(!result.contains("请求成功")){
logger.error("请求出现异常:"+result);
return Result.error("请求出现异常");
}else{
OcrResultEo ocrResultEo = JSONObject.parseObject(responseEntity.getBody(), OcrResultEo.class);
OcrResultEo ocrResultEo = JSONObject.parseObject(result, OcrResultEo.class);
if(ocrResultEo.getResultCode().equals("0")){
if ("add".equals(type)) {
OcrRecordEO ocrRecordEO = new OcrRecordEO();
@@ -0,0 +1,193 @@
package com.adc.da.ocr.util;
import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
/**
*
* @author David
*/
@Component
public class OkHttpUtil {
private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);
@Autowired
private OkHttpClient okHttpClient;
/**
* get
*
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @return
*/
public String get(String url, Map<String, String> queries, Map<String, String> headerParams) {
String responseBody = "";
StringBuffer sb = new StringBuffer(url);
if (queries != null && queries.keySet().size() > 0) {
boolean firstFlag = true;
Iterator iterator = queries.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry<String, String>) iterator.next();
if (firstFlag) {
sb.append("?" + entry.getKey() + "=" + entry.getValue());
firstFlag = false;
} else {
sb.append("&" + entry.getKey() + "=" + entry.getValue());
}
}
}
Request.Builder requestBuilder = new Request.Builder().url(url);
if(headerParams != null){
for(Map.Entry<String, String> entry : headerParams.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
}
Request request = requestBuilder.url(sb.toString())
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (status == 200) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp put error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* post
*
* @param url 请求的url
* @param params post form 提交的参数
* @return
*/
public String post(String url, Map<String, String> params, Map<String, String> headerParams) {
String responseBody = "";
FormBody.Builder builder = new FormBody.Builder();
//添加参数
if (params != null && params.keySet().size() > 0) {
for (String key : params.keySet()) {
builder.add(key, params.get(key));
}
}
Request.Builder requestBuilder = new Request.Builder().url(url);
for(Map.Entry<String, String> entry : headerParams.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
Request request = requestBuilder.post(builder.build()).build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (status == 200) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp post error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* post
*
* @param url 请求的url
* @param params post form 提交的参数
* @return
*/
public String postForJson(String url, String json, Map<String, String> headerParams) {
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);
String responseBody = "";
Request.Builder requestBuilder = new Request.Builder().url(url);
for(Map.Entry<String, String> entry : headerParams.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
Request request = requestBuilder.post(requestBody).build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (status == 200) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp post error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* post 上传文件
*
* @param url
* @param params
* @param fileType
* @return
*/
public String postFile(String url, Map<String, Object> params, String fileType, Map<String, String> headerParams) {
String responseBody = "";
MultipartBody.Builder builder = new MultipartBody.Builder();
//添加参数
if (params != null && params.keySet().size() > 0) {
for (String key : params.keySet()) {
if (params.get(key) instanceof File) {
File file = (File) params.get(key);
builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(fileType), file));
continue;
}
builder.addFormDataPart(key, params.get(key).toString());
}
}
Request.Builder requestBuilder = new Request.Builder();
for(Map.Entry<String, String> entry : headerParams.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
Request request = requestBuilder.url(url).post(builder.build()).build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (status == 200) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp postFile error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
}