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


}
相关推荐
胖胖胖胖胖虎4 小时前
okhttp Stream Load 含认证请求重定向
starrocks·okhttp
步十人11 小时前
【JavaScript】通过AJAX技术让前端发请求到后端
javascript·ajax·okhttp
XiYang-DING11 小时前
【Spring】 Ajax
spring·ajax·okhttp
hj10431 天前
fastadmin 开发示例:使用 layer 弹窗实现数据快速录入
okhttp
YF02115 天前
Android App 高效升级指南:OkDownload 多线程断点续传与全版本安装适配
android·okhttp·app
YF02117 天前
深度解构Android OkDownload断点续传
android·数据库·okhttp
右耳朵猫AI10 天前
Python技术周刊 2026年第14周
开发语言·python·okhttp
牢七10 天前
cve研究
okhttp
yqcoder11 天前
原生 AJAX 揭秘:如何使用 XHR 发起请求
前端·ajax·okhttp
身如柳絮随风扬14 天前
你知道什么是 Ajax 吗?—— 从入门到原理,一篇彻底搞懂
前端·ajax·okhttp