欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java+Okhttp3調(diào)用接口的實(shí)例

 更新時(shí)間:2023年12月16日 10:07:23   作者:木昜楊的書  
這篇文章主要介紹了java+Okhttp3調(diào)用接口的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

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è)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論