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


}
相关推荐
曹绍华11 小时前
okhttp建造者模式详解
okhttp·建造者模式
chilavert3182 天前
技术演进中的开发沉思-200 JavaScript:YUI 的AJAX 动态加载机制
javascript·ajax·okhttp
永远的WEB小白3 天前
wordpress自定义订阅邮件发送
okhttp
曹绍华6 天前
okhttp详解
okhttp
天花板之恋9 天前
Android http网络请求的那些事儿
http·okhttp
Entropless9 天前
解剖OkHttp:那些主流教程未曾深入的设计精髓
android·okhttp
介一安全10 天前
【Frida Android】实战篇3:基于 OkHttp 库的 Hook 抓包
android·okhttp·网络安全·frida
峰哥的Android进阶之路11 天前
Okhttp原理总结
okhttp
椰羊sqrt14 天前
CVE-2025-4334 深度分析:WordPress wp-registration 插件权限提升漏洞
android·开发语言·okhttp·网络安全