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


}
相关推荐
zhangjin11208 天前
Okhttp系列:POST请求
okhttp
এ慕ོ冬℘゜11 天前
深入理解 JavaScript 事件体系:Window、鼠标与键盘事件详解
开发语言·javascript·okhttp
牢七13 天前
wordpress
okhttp
脉动数据行情16 天前
Java OkHttp 完整封装 GC COMEX 美黄金实时盘口定时拉取工具类
java·okhttp·comex 黄金·外盘贵金属
帅次17 天前
Android 高级工程师面试:网络与数据层 近1年高频追问 18 题
android·网络·okhttp·面试·retrofit·gilde
Java面试题总结18 天前
fastadmin 新手部分功能点
okhttp
殳翰22 天前
向客户端提供JSON数据的方式
okhttp·json
CYY951 个月前
OkHttp 和 Retrofit 封装使用
okhttp·retrofit
CYY951 个月前
OkHttp 的使用
okhttp
朝星1 个月前
Android开发[14]:网络优化之OkHttp
android·okhttp·kotlin