OKHttpUtils

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import okhttp3.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 
 * @version 1.0
 * @date 2022/4/21 14:21
 * @desc 测试
 */
public class OKHttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(OKHttpUtil2.class);

    /**
     * 通过表单数据参数填入
     * @param url 请求地址
     * @param bodyMap 请求参数
     * @return JSONObject
     */
    public JSONObject JSONObjectByMap(String url, Map<String,Object> bodyMap) {

        Response response = ResponseByMap(url, bodyMap, HTTP_METHOD.GET, null);
        try {
            String result = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(result);//转为JSON格式
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 通过表单数据参数填入
     * @param url 请求地址
     * @param bodyMap 请求参数
     * @param type 请求方式
     * @return JSONObject
     */
    public JSONObject JSONObjectByMap(String url, Map<String,Object> bodyMap, HTTP_METHOD type) {

        Response response = ResponseByMap(url, bodyMap, type, null);
        try {
            String result = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(result);//转为JSON格式
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过表单数据参数填入
     * @param url 请求地址
     * @param bodyMap 请求参数
     * @param headers 设置请求头信息
     * @return JSONObject
     */
    public JSONObject JSONObjectByMap(String url, Map<String,Object> bodyMap, Map<String,String> headers) {

        Response response = ResponseByMap(url, bodyMap, HTTP_METHOD.GET, headers);
        try {
            String result = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(result);//转为JSON格式
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 通过表单数据参数填入
     * @param url 请求地址
     * @param bodyMap 请求参数
     * @return Response
     */
    public Response ResponseByMap(String url, Map<String,Object> bodyMap) {
        return ResponseByMap(url,bodyMap, HTTP_METHOD.GET,null);
    }
    /**
     * 通过表单数据参数填入
     * @param url 请求地址
     * @param bodyMap 请求参数
     * @param type 请求方式
     * @return Response
     */
    public Response ResponseByMap(String url, Map<String,Object> bodyMap, HTTP_METHOD type) {
        Response response = ResponseByMap(url, bodyMap, type, null);
        if (ObjectUtils.isEmpty(response)) {
            throw new RuntimeException(String.format("请求地址:{},response为空", url));
        }
        if (HttpStatus.OK.value() != response.code()) {
            throw new RuntimeException();
        }
        return response;
    }
    /**
     * 通过表单数据参数填入
     * @param url 请求地址
     * @param bodyMap 请求参数
     * @param headers 设置请求头信息
     * @return Response
     */
    public Response ResponseByMap(String url, Map<String,Object> bodyMap,Map<String,String> headers) {
        return ResponseByMap(url,bodyMap, HTTP_METHOD.GET,headers);
    }

    /**
     * 通过表单数据参数填入
     * @param url 请求地址
     * @param bodyMap 请求参数
     * @param type 请求方式
     * @param headers 设置请求头信息
     * @return Response
     */
    public static Response ResponseByMap(String url, Map<String,Object> bodyMap, HTTP_METHOD type, Map<String,String> headers) {

        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .build();

        FormBody.Builder builder = new FormBody.Builder();
        if (bodyMap !=null){
            bodyMap.forEach((k,v)->{
                if (v==null){
                    return;
                }
                builder.add(k,v.toString());
            });
        }
        RequestBody requestBody = builder.build();

        Request.Builder requestBuilder = new Request.Builder();
        // 设置请求方式
        if(ObjectUtils.isNotEmpty(type) && type== HTTP_METHOD.POST){
            requestBuilder.post(requestBody);
            requestBuilder.url(url);
        } else if (ObjectUtils.isNotEmpty(type) && type== HTTP_METHOD.PUT){
            requestBuilder.put(requestBody);
            requestBuilder.url(url);
        } else if (ObjectUtils.isNotEmpty(type) && type== HTTP_METHOD.DELETE){
            requestBuilder.delete(requestBody);
            requestBuilder.url(url);
        } else if (ObjectUtils.isNotEmpty(type) && type== HTTP_METHOD.GET) {
            StringBuffer sb = getQueryString(url, bodyMap);
            requestBuilder.url(sb.toString());
        }

        //设置请求头
        if(CollectionUtils.isNotEmpty(headers)){
            requestBuilder.headers(Headers.of(headers));
        }
        Request request = requestBuilder.build();

        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /* 以上通过通过表单方式提交请求, 以下通过Json方式提交请求*/

    /**
     * 通过json数据参数填入
     * @param url 请求地址
     * @param jsonParams json请求头
     * @param type 请求方式
     * @param headers 设置请求头信息
     * @return Response
     */
    public static Response ResponseByJsonParams(String url, String jsonParams, HTTP_METHOD type, Map<String,String> headers) {

        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .build();

        Request.Builder requestBuilder = new Request.Builder();
        RequestBody requestBody = null;
        // 设置请求体内容
        if (StringUtils.isNotEmpty(jsonParams)){
            requestBody = RequestBody.create(jsonParams, MediaType.parse("application/json; charset=utf-8"));
        }
        // 设置请求方式
        if(ObjectUtils.isNotEmpty(type) && type== HTTP_METHOD.POST){
            requestBuilder.post(requestBody);
            requestBuilder.url(url);
        } else if (ObjectUtils.isNotEmpty(type) && type== HTTP_METHOD.PUT){
            requestBuilder.put(requestBody);
            requestBuilder.url(url);
        } else if (ObjectUtils.isNotEmpty(type) && type== HTTP_METHOD.DELETE){
            requestBuilder.delete(requestBody);
            requestBuilder.url(url);
        } else if (ObjectUtils.isNotEmpty(type) && type== HTTP_METHOD.GET) {
            requestBuilder.url(url);
        }

        //设置请求头
        if(CollectionUtils.isNotEmpty(headers)){
            requestBuilder.headers(Headers.of(headers));
        }
        Request request = requestBuilder.build();

        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            if (ObjectUtils.isEmpty(response)) {
                throw new RuntimeException(String.format("请求地址:{},response为空", url));
            }
            if (HttpStatus.OK.value() != response.code()) {
                throw new RuntimeException();
            }
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据map获取get请求参数
     *
     * @param queries
     * @return
     */
    public static StringBuffer getQueryString(String url, Map<String, Object> queries) {

        StringBuffer sb = new StringBuffer(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        logger.info("http请求地址为:{}", sb.toString());
        return sb;
    }

    enum HTTP_METHOD {
        GET,
        POST,
        PUT,
        DELETE,
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值