Okhttp通用工具类

  • 通用get和post请求
java 复制代码
import cn.hutool.json.JSONUtil;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;

/**
 * @ClassName OkHttpUtils
 * @description: http客户端远程调用通用工具类
 * @author: chenlf
 * @Version 1.0
 **/
public class OkHttpUtils {

    private static OkHttpClient client = new OkHttpClient();

    public static String execute(String url, String method, RequestBody requestBody, Map<String, String> headers){
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .method(method, requestBody);

        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        try (Response response = client.newCall(requestBuilder.build()).execute()) {
            if (!response.isSuccessful())
                throw new IOException("远程调用接口失败:" + response);
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static String doGet(String url){
        return execute(url, "GET", null, null);
    }

    public static String doGet(String url, Map<String, String> headers){
        return execute(url, "GET", null, headers);
    }

    public static String doPost(String url, String jsonBody){
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSONUtil.toJsonStr(jsonBody));
        return execute(url, "POST", body, null);
    }

    public static String doPost(String url, RequestBody body){
        return execute(url, "POST", body, null);
    }

    public static String doPost(String url, String jsonBody, Map<String, String> headers){
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSONUtil.toJsonStr(jsonBody));
        return execute(url, "POST", body, headers);
    }
    public static String doPost(String url, RequestBody body, Map<String, String> headers){
        return execute(url, "POST", body, headers);
    }


}
相关推荐
北冥SP8 小时前
OkHttp连接池
网络·okhttp
zhougl9969 小时前
OkHttp用法-Java调用http服务
java·http·okhttp
Go_going_1 天前
ajax,Promise 和 fetch
javascript·ajax·okhttp
xzkyd outpaper4 天前
okhttp原理
okhttp
酷小洋6 天前
Ajax基础
前端·ajax·okhttp
人间有清欢8 天前
Android开发补充内容
android·okhttp·rxjava·retrofit·hilt·jetpack compose
diaostar10 天前
Android OKHttp原理简单说明
android·okhttp
yuren_xia17 天前
Spring MVC 中解决中文乱码问题
spring·okhttp·mvc
我要喝可乐!18 天前
OkHttp源码梳理
网络协议·http·okhttp
前端熊猫21 天前
jQuery AJAX、Axios与Fetch
ajax·okhttp·jquery