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 天前
1688商品数据抓取:Python爬虫+动态页面解析
爬虫·python·okhttp
minos.cpp5 天前
第一章 OkHttp 是怎么发出一个请求的?——整体流程概览
android·okhttp·面试
Sy_planA8 天前
介绍一下jQuery的AJAX异步请求
ajax·okhttp·jquery
2401_8370885014 天前
AJAX简介
okhttp
2401_8370885016 天前
Axios介绍
android·okhttp
魑魅魍魉都是鬼21 天前
白玩 一 记录retrofit+okhttp+flow 及 kts的全局配置
okhttp·retrofit
小白学大数据22 天前
Python + Requests库爬取动态Ajax分页数据
开发语言·python·ajax·okhttp
小毛驴8501 个月前
JavaScript AJAX 实现,演示如何将 Token 添加到 Authorization
javascript·ajax·okhttp
安卓开发者1 个月前
OkHttp 与 Room 结合使用:构建高效的 Android 本地缓存策略
android·okhttp·缓存
安卓开发者1 个月前
OkHttp 与 Chuck 结合使用:优雅的 Android 网络请求调试方案
android·okhttp