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


}
相关推荐
小白学大数据10 小时前
Python + Requests库爬取动态Ajax分页数据
开发语言·python·ajax·okhttp
小毛驴8506 天前
JavaScript AJAX 实现,演示如何将 Token 添加到 Authorization
javascript·ajax·okhttp
安卓开发者7 天前
OkHttp 与 Room 结合使用:构建高效的 Android 本地缓存策略
android·okhttp·缓存
安卓开发者7 天前
OkHttp 与 Chuck 结合使用:优雅的 Android 网络请求调试方案
android·okhttp
安卓开发者7 天前
OkHttp 与 RxJava/RxAndroid 完美结合:构建响应式网络请求架构
okhttp·架构·rxjava
安卓开发者7 天前
OkHttp 与 Glide 完美结合:打造高效的 Android 图片加载方案
android·okhttp·glide
安卓开发者7 天前
OkHttp 与 Stetho 结合使用:打造强大的 Android 网络调试工具链
android·okhttp
二向箔reverse7 天前
Selenium 处理动态网页与等待机制详解
okhttp
CYRUS_STUDIO8 天前
彻底搞懂 Retrofit:使用、封装与 Converter 原理
android·okhttp·retrofit
娅娅梨10 天前
HarmonyOS-ArkUI Web控件基础铺垫4--TCP协议- 断联-四次挥手解析
网络协议·tcp/ip·http·okhttp·harmonyos·arkui·arkweb