java+Okhttp3調(diào)用接口的實(shí)例
application.yml層的接口配置
ocr: generalUrl: http://localhost:9000/ocr/general #常規(guī)識(shí)別接口地址 toOFDUrl: http://localhost:9000/ocr/toOFD #識(shí)別并生成ofd文件接口地址 queryUrl: http://localhost:9000/ocr/query #查詢結(jié)果接口地址 fetchUrl: http://localhost:9000/ocr/fetch #獲取結(jié)果接口地址
以方便后期對(duì)接口地址進(jìn)行更改替換
OkhttpAPI.java 工具類(接口的調(diào)用)
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ī)識(shí)別 * @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轉(zhuǎn)為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"); //拼裝參數(shù) 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(); //獲取反饋內(nèi)容 result = response.body().string(); } catch (Exception e) { e.printStackTrace(); System.out.println("上傳失敗"); } finally { deleteTempFile(file); } return result; } /** * 識(shí)別并生成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轉(zhuǎn)為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"); //拼裝參數(shù) 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(); //獲取反饋內(nèi)容 result = response.body().string(); } catch (Exception e) { e.printStackTrace(); System.out.println("上傳失敗"); } finally { deleteTempFile(file); } return result; } /** * 查詢結(jié)果 * 同步請(qǐng)求 * @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}; //拼裝參數(shù) 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(); } } /** * 查詢結(jié)果 * 異步請(qǐng)求 * @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 = {""}; //拼裝參數(shù) 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去請(qǐng)求 call.enqueue(new Callback() {//4.回調(diào)方法 public void onFailure(Call call, IOException e) { System.err.println("返回的結(jié)果的值失敗"); } public void onResponse(Call call, Response response) throws IOException { String result = response.body().string();//5.獲得網(wǎng)絡(luò)數(shù)據(jù) msg[0] = msg[0] + result; System.out.println(result); } }); return msg[0]; } /** * 獲取結(jié)果 * 同步請(qǐng)求 * @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}; //拼裝參數(shù) 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(); } } }
因?yàn)轫?xiàng)目需要每個(gè)請(qǐng)求都加有條件和傳輸類型,各位根據(jù)自己的需要進(jìn)行修改即可。
OcrServiceImpl.java 調(diào)用實(shí)例
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 { // 超時(shí)時(shí)間設(shè)置為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ī)識(shí)別 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"); //查詢結(jié)果 OkHttpApi api_query = new OkHttpApi(); long requestTime = System.currentTimeMillis(); String msg =""; //get查詢結(jié)果 //1 如果沒(méi)請(qǐng)求到則輪詢,直到獲取內(nèi)容或超時(shí) while((System.currentTimeMillis() - requestTime) < TIMEOUT){ String getbody = api_query.getEXBody(id,type,queryUrl); //將獲取到的getbody換成json對(duì)象 JSONObject objbody = JSON.parseObject(getbody); //2.獲取json字符串的result部分 String strresult = objbody.getString("result"); if (strresult != null) { //3.將result部分再轉(zhuǎn)為Json數(shù)組 JSONArray objArray = JSON.parseArray(strresult); //4.根據(jù)數(shù)組長(zhǎng)度取出每一頁(yè) for (int i = 0; i < objArray.size();i++){ //獲取每一頁(yè)的內(nèi)容 String list = objArray.getString(i); //將獲得的內(nèi)容json格式化 JSONObject objcontent = JSON.parseObject(list); //獲取content中的內(nèi)容 String strcontent = objcontent.getString("content"); //將content部分再轉(zhuǎn)化為json數(shù)組 JSONArray artcontent = JSON.parseArray(strcontent); //5.取出每一頁(yè)當(dāng)中的值 for (int j = 0; j < artcontent.size();j++){ //獲取頁(yè)面當(dāng)中的內(nèi)容 String content = artcontent.getJSONObject(j).getString("text"); msg = msg + content + "\r\n"; } msg = msg + "\r\n"; } break; // 跳出循環(huán),返回?cái)?shù)據(jù) } else { Thread.sleep(1000);// 休眠1秒 } } message = msg; //識(shí)別并生成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查詢結(jié)果 while((System.currentTimeMillis() - requestTime) < TIMEOUT){ String getbody = api.getEXBody(ofdid,ofdtype,queryUrl); //1.將獲取到的getbody換成json對(duì)象 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; } }
根據(jù)自己的需求對(duì)調(diào)用的接口進(jìn)行數(shù)據(jù)處理
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Java如何基于okhttp請(qǐng)求SSE接口流式返回詳解
- Java請(qǐng)求Http接口OkHttp超詳細(xì)講解(附帶工具類)
- Java中的HttpServletRequest接口詳細(xì)解讀
- Java調(diào)用HTTPS接口實(shí)現(xiàn)繞過(guò)SSL認(rèn)證
- Java調(diào)用第三方http接口的四種方式總結(jié)
- Java發(fā)送http請(qǐng)求調(diào)用第三方接口獲取token方式
- Java調(diào)用第三方http接口的常用方式總結(jié)
- Java實(shí)現(xiàn)調(diào)用對(duì)方http接口得到返回?cái)?shù)據(jù)
- Java 調(diào)用 HTTP 接口的 7 種方式示例代碼(全網(wǎng)最全指南)
相關(guān)文章
SpringBoot實(shí)現(xiàn)識(shí)別圖片中的身份證號(hào)與營(yíng)業(yè)執(zhí)照信息
這篇文章主要為大家詳細(xì)介紹了SpringBoot如何實(shí)現(xiàn)識(shí)別圖片中的身份證號(hào)與營(yíng)業(yè)執(zhí)照信息,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2024-01-01郵件收發(fā)原理你了解嗎? 郵件發(fā)送基本過(guò)程與概念詳解(一)
你真的了解郵件收發(fā)原理嗎?這篇文章主要為大家詳細(xì)介紹了郵件發(fā)送基本過(guò)程與概念,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10SpringBoot配置文件導(dǎo)入方法詳細(xì)講解
Spring Boot雖然是Spring的衍生物, 但默認(rèn)情況下Boot是不能直接使用Spring的配置文件的, 我們可以通過(guò)兩種方式導(dǎo)入Spring的配置2022-10-10Java基于FFmpeg實(shí)現(xiàn)Mp4視頻轉(zhuǎn)GIF
FFmpeg是一套可以用來(lái)記錄、轉(zhuǎn)換數(shù)字音頻、視頻,并能將其轉(zhuǎn)化為流的開(kāi)源計(jì)算機(jī)程序。本文主要介紹了在Java中如何基于FFmpeg進(jìn)行Mp4視頻到Gif動(dòng)圖的轉(zhuǎn)換,感興趣的小伙伴可以了解一下2022-11-11Springboot + Mysql8實(shí)現(xiàn)讀寫分離功能
這篇文章主要介紹了Springboot + Mysql8實(shí)現(xiàn)讀寫分離功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-10-10Mybatis中自定義TypeHandler處理枚舉的示例代碼
typeHandler,是 MyBatis 中的一個(gè)接口,用于處理數(shù)據(jù)庫(kù)中的特定數(shù)據(jù)類型,下面簡(jiǎn)單介紹創(chuàng)建自定義 typeHandler 來(lái)處理枚舉類型的示例,感興趣的朋友跟隨小編一起看看吧2024-01-01