java+Okhttp3調用接口的實例
更新時間:2023年12月16日 10:07:23 作者:木昜楊的書
這篇文章主要介紹了java+Okhttp3調用接口的實例,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
application.yml層的接口配置
ocr: generalUrl: http://localhost:9000/ocr/general #常規(guī)識別接口地址 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 { /** * 常規(guī)識別 * @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; 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(toOFDUrl) .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; } /** * 查詢結果 * 同步請求 * @param id 查詢的id * @param type 查詢的type * @return * @throws IOException */ public String getEXBody(String id,String type,String queryUrl) throws IOException { OkHttpClient client = new OkHttpClient().newBuilder() .connectionPool(new ConnectionPool()) .connectTimeout(30000, TimeUnit.MILLISECONDS) .readTimeout(100000, TimeUnit.MILLISECONDS) .build(); final String[] body = {null}; //拼裝參數 String url = queryUrl + "?id="+id+"&type="+type; Request request = new Request.Builder() .url(url) .header("id",id) .header("type",type) .build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } /** * 查詢結果 * 異步請求 * @param id 查詢的id * @param type 查詢的type * @return * @throws IOException */ public String getEQBody(String id,String type,String queryUrl) throws IOException { OkHttpClient client = new OkHttpClient().newBuilder() .connectionPool(new ConnectionPool()) .connectTimeout(50000, TimeUnit.MILLISECONDS) .readTimeout(100000, TimeUnit.MILLISECONDS) .build(); final String[] msg = {""}; //拼裝參數 String url = queryUrl + "?id=" + id + "&type=" + type; Request request = new Request.Builder() .url(url) .header("id",id) .header("type",type) .build(); Call call = client.newCall(request);//3.使用client去請求 call.enqueue(new Callback() {//4.回調方法 public void onFailure(Call call, IOException e) { System.err.println("返回的結果的值失敗"); } public void onResponse(Call call, Response response) throws IOException { String result = response.body().string();//5.獲得網絡數據 msg[0] = msg[0] + result; System.out.println(result); } }); return msg[0]; } /** * 獲取結果 * 同步請求 * @param id 查詢的id * @return * @throws IOException */ public String getOfdBody(String id,String fetchUrl) throws IOException { OkHttpClient client = new OkHttpClient().newBuilder() .connectionPool(new ConnectionPool()) .connectTimeout(30000, TimeUnit.MILLISECONDS) .readTimeout(100000, TimeUnit.MILLISECONDS) .build(); final String[] body = {null}; //拼裝參數 String url = fetchUrl + "?id="+id; Request request = new Request.Builder() .url(url) .header("id",id) .build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } }
因為項目需要每個請求都加有條件和傳輸類型,各位根據自己的需要進行修改即可。
OcrServiceImpl.java 調用實例
package com.ocr.ocr.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.ocr.ocr.service.OcrService; import com.ocr.ocr.utils.OkHttpApi; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; /** * @author dayang * @date 2021/12/27 14:11 */ @Service public class OcrServiceImpl implements OcrService { // 超時時間設置為30秒 private static final long TIMEOUT = 60000; @Value("${ocr.generalUrl}") private String generalUrl; @Value("${ocr.toOFDUrl}") private String toOFDUrl; @Value("${ocr.queryUrl}") private String queryUrl; @Value("${ocr.fetchUrl}") private String fetchUrl; private String fileName; private String fileType; private String fileSize; private String message; private String ofdId; private String ofdType; private String ofdUrl; @Override public String uploadFile(MultipartFile file) throws Exception { DecimalFormat df = new DecimalFormat("#.00"); fileName = file.getOriginalFilename(); //常規(guī)識別 OkHttpApi api_general = new OkHttpApi(); String ocr = api_general.ocrFilePost(file,fileName,generalUrl); JSONObject jsonObject = JSON.parseObject(ocr); String id = jsonObject.getString("id"); String type = jsonObject.getString("type"); //查詢結果 OkHttpApi api_query = new OkHttpApi(); long requestTime = System.currentTimeMillis(); String msg =""; //get查詢結果 //1 如果沒請求到則輪詢,直到獲取內容或超時 while((System.currentTimeMillis() - requestTime) < TIMEOUT){ String getbody = api_query.getEXBody(id,type,queryUrl); //將獲取到的getbody換成json對象 JSONObject objbody = JSON.parseObject(getbody); //2.獲取json字符串的result部分 String strresult = objbody.getString("result"); if (strresult != null) { //3.將result部分再轉為Json數組 JSONArray objArray = JSON.parseArray(strresult); //4.根據數組長度取出每一頁 for (int i = 0; i < objArray.size();i++){ //獲取每一頁的內容 String list = objArray.getString(i); //將獲得的內容json格式化 JSONObject objcontent = JSON.parseObject(list); //獲取content中的內容 String strcontent = objcontent.getString("content"); //將content部分再轉化為json數組 JSONArray artcontent = JSON.parseArray(strcontent); //5.取出每一頁當中的值 for (int j = 0; j < artcontent.size();j++){ //獲取頁面當中的內容 String content = artcontent.getJSONObject(j).getString("text"); msg = msg + content + "\r\n"; } msg = msg + "\r\n"; } break; // 跳出循環(huán),返回數據 } else { Thread.sleep(1000);// 休眠1秒 } } message = msg; //識別并生成OFD OkHttpApi api_toOFD = new OkHttpApi(); String ofd = api_toOFD.ocrFileToOfd(file,file.getOriginalFilename(),toOFDUrl); JSONObject jsonObject1 = JSON.parseObject(ofd); ofdId = jsonObject1.getString("id"); ofdType = jsonObject1.getString("type"); fileType = file.getContentType(); if (file.getSize() < 1024){ fileSize = df.format((double) file.getSize()) + "B"; } else if (file.getSize() < 1048576){ fileSize = df.format((double) file.getSize() / 1024) + "KB"; } else if (file.getSize() < 1073741824){ fileSize = df.format((double) file.getSize() / 1048576) + "MB"; } else{ fileSize = df.format((double) file.getSize() / 1073741824) + "GB"; } return "上傳成功"; } @Override public String downloadById(String ofdid,String ofdtype) throws Exception { //獲取ofd url地址 OkHttpApi api = new OkHttpApi(); long requestTime = System.currentTimeMillis(); //get查詢結果 while((System.currentTimeMillis() - requestTime) < TIMEOUT){ String getbody = api.getEXBody(ofdid,ofdtype,queryUrl); //1.將獲取到的getbody換成json對象 JSONObject objbody = JSON.parseObject(getbody); //2.獲取json字符串的result部分 String success = objbody.getString("success"); String fetch = objbody.getString("fetch"); if (fetch != null){ if (success.equals("true") && fetch.equals("true")){ OkHttpApi apiofd = new OkHttpApi(); String ofd = apiofd.getOfdBody(ofdid,fetchUrl); if (!ofd.isEmpty()){ ofdUrl = fetchUrl +"?id="+ ofdid; } } break; }else { Thread.sleep(1000);// 休眠1秒 } } return ofdUrl; } @Override public Map<String, String> maplist() { Map<String,String> map = new HashMap<>(); map.put("filename",fileName); map.put("filetype",fileType); map.put("filesize",fileSize); map.put("msg",message); map.put("ofdid",ofdId); map.put("ofdtype",ofdType); return map; } }
根據自己的需求對調用的接口進行數據處理
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot實現(xiàn)識別圖片中的身份證號與營業(yè)執(zhí)照信息
這篇文章主要為大家詳細介紹了SpringBoot如何實現(xiàn)識別圖片中的身份證號與營業(yè)執(zhí)照信息,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2024-01-01郵件收發(fā)原理你了解嗎? 郵件發(fā)送基本過程與概念詳解(一)
你真的了解郵件收發(fā)原理嗎?這篇文章主要為大家詳細介紹了郵件發(fā)送基本過程與概念,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10Springboot + Mysql8實現(xiàn)讀寫分離功能
這篇文章主要介紹了Springboot + Mysql8實現(xiàn)讀寫分離功能,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10Mybatis中自定義TypeHandler處理枚舉的示例代碼
typeHandler,是 MyBatis 中的一個接口,用于處理數據庫中的特定數據類型,下面簡單介紹創(chuàng)建自定義 typeHandler 來處理枚舉類型的示例,感興趣的朋友跟隨小編一起看看吧2024-01-01