java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java+Okhttp3调用接口

java+Okhttp3调用接口的实例

作者:木昜楊的书

这篇文章主要介绍了java+Okhttp3调用接口的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

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;
        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();

        //常规识别
        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; // 跳出循环,返回数据
            } 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;
    }

}

根据自己的需求对调用的接口进行数据处理

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文