前言:一般Java项目后端发送请求都使用http,最近项目里面大佬建议把http都改成okhttp3(OkHttpClient)。故今日记录部分常用发送方式。

 

代码:为了便于以后使用,这里封装一个OkHttpUtil的工具类

   1、先导入jar包:

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
   <version>3.9.0</version>
</dependency>

 

  2、OkHttpUtil的工具类:

package cn.wj.fdata.util;

import com.alibaba.fastjson.JSON;
import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.lang3.exception.ExceptionUtils;

@Slf4j
public class OkHttpUtil {

    public static final MediaType jsonType = MediaType.parse("application/json; charset=utf-8");

    public static final MediaType mediaType = MediaType.parse("application/octet-stream");

    public final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(8000, TimeUnit.MILLISECONDS)
            .readTimeout(8000, TimeUnit.MILLISECONDS)
            .build();

    /**
     * 发送post请求通过Form表单形式
     *
     * @param reqUrl 请求url
     * @param mapParam 请求参数
     *
     */
    private void sendPostByForm(String reqUrl, Map<String,String> mapParam){
        try {
            long startTime = System.currentTimeMillis();
            //循环form表单,将表单内容添加到form builder中
            FormBody.Builder formBody = new FormBody.Builder();
            for (Map.Entry<String, String> m : mapParam.entrySet()) {
                String name = m.getKey();
                String value = m.getValue()+"";
                formBody.add(name, value);
            }
            //构建formBody(formBody.build()),将其传入Request请求中
            Request.Builder builder = new Request.Builder().url(reqUrl).post(formBody.build());
            try(Response response = okHttpClient.newCall(builder.build()).execute()){
                String body = response.body().string();
                log.info("{} response body:{}", reqUrl.substring(reqUrl.lastIndexOf("/") + 1),
                        body);
            }catch(Exception e){
                log.error("调用接口出错\n"+ ExceptionUtils.getMessage(e));
            }finally{
                long endTime = System.currentTimeMillis();
                log.info("{} cost time:{}", reqUrl.substring(reqUrl.lastIndexOf("/") + 1),
                        (endTime - startTime));
            }
        } catch (Exception e) {
            log.error("error", e);
        }
    }

    /**
     * 发送post请求通过JSON参数
     *
     * @param reqUrl 请求url
     * @param param 请求参数
     *
     */
    private void sendPostByJson(String reqUrl, Object param){
        try {
            String paramStr = JSON.toJSONString(param);

            RequestBody requestBody = RequestBody.create(jsonType, paramStr);
            long startTime = System.currentTimeMillis();
            Request.Builder builder = new Request.Builder().url(reqUrl).post(requestBody);

            try(Response response = okHttpClient.newCall(builder.build()).execute()){
                String body = response.body().string();
            }catch(Exception e){
                log.error("调用接口出错\n"+ ExceptionUtils.getMessage(e));
            }finally{
                long endTime = System.currentTimeMillis();
                log.info("{} cost time:{}", reqUrl.substring(reqUrl.lastIndexOf("/") + 1),
                        (endTime - startTime));
            }
        } catch (Exception e) {
            log.error("error", e);
        }
    }

    /**
     * 上传文件
     *
     * @param reqUrl 请求url
     * @param file 上传的文件
     * @param fileName 文件名称
     *
     */
    public void uploadFile(String reqUrl, File file, String fileName) {
        try {
            RequestBody fileBody = RequestBody.create(mediaType, file);
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("fileName", fileName)
                    .addFormDataPart("file", fileName, fileBody).build();

            long startTime = System.currentTimeMillis();
            Request.Builder builder = new Request.Builder().url(reqUrl).post(requestBody);

            try(Response response = okHttpClient.newCall(builder.build()).execute()){
                String body = response.body().string();
            }catch(Exception e){
                log.error("调用接口出错\n"+ ExceptionUtils.getMessage(e));
            }finally{
                long endTime = System.currentTimeMillis();
                log.info("{} cost time:{}", reqUrl.substring(reqUrl.lastIndexOf("/") + 1),
                        (endTime - startTime));
            }
        } catch (Exception e) {
            log.error("error", e);
        }
    }
}

 

参考文章:

文章1

文章2

 

完!

 

posted on 2021-02-08 19:51  半纸情书  阅读(4387)  评论(0编辑  收藏  举报