okhttp3动态请求api接口
application.yml层的接口配置
ocr:
generalUrl: http://localhost:9000/ocr/general #常规识别接口地址
toOFDUrl: http://localhost:9000/ocr/toOFD #识别并生成ofd文件接口地址
queryUrl: http://localhost:9000/ocr/query #查询结果接口地址
fetchUrl: http://localhost:9000/ocr/fetch #获取结果接口地址
以方便后期对接口地址进行更改替换
OkhttpAPI.java 工具类(接口的调用)
package com.ocr.ocr.utils;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.concurrent.TimeUnit;
import static com.ocr.ocr.utils.MultipartFileToFile.deleteTempFile;
import static com.ocr.ocr.utils.MultipartFileToFile.multipartFileToFile;
/**
* @author dayang
* @date 2021/12/23 16:30
*/
public class OkHttpApi {
/**
* 常规识别
* @param multiFile 文件
* @param filename 文件名
* @return
* @throws Exception
*/
public String ocrFilePost(MultipartFile multiFile, String filename,String generalUrl) throws Exception{
File file = null;
String result = null;
String type = "";
try {
//将MultipartFile转为File
file = multipartFileToFile(multiFile);
//获取文件格式
String suffix = filename.substring(filename.lastIndexOf(".") + 1);
if (suffix.equals("pdf")){
type = type + suffix;
}else if (suffix.equals("ofd")){
type = type + suffix;
}else{
type = type + "img";
}
// file是要上传的文件 File()
RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
OkHttpClient client = new OkHttpClient().newBuilder().build();
// MediaType mediaType = MediaType.parse("text/plain");
//拼装参数
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file",filename)
.addFormDataPart("format",type)
.addFormDataPart("file",multiFile.getOriginalFilename(),fileBody)
.build();
//路径
Request request = new Request.Builder()
.url(generalUrl)
.method("POST", body)
.build();
Response response = client.newCall(request).execute();
//获取反馈内容
result = response.body().string();
} catch (Exception e) {
e.printStackTrace();
System.out.println("上传失败");
} finally {
deleteTempFile(file);
}
return result;
}
/**
* 识别并生成ofd
* @param multiFile 文件
* @param filename 文件名
* @return
* @throws Exception
*/
public String ocrFileToOfd(MultipartFile multiFile, String filename,String toOFDUrl) throws Exception{
File file = null