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


}
相关推荐
初见_Dream19 小时前
Retrofit+OkHttp+ViewModel
xml·okhttp·retrofit
清风细雨_林木木2 天前
wangEditor 编辑器 Vue 2.0 + Nodejs 配置
vue.js·okhttp·编辑器
WeiLai11127 天前
DeepSeekApi对接流式输出异步聊天功能:基于Spring Boot和OkHttp的SSE应用实现
人工智能·spring boot·后端·okhttp
闲暇部落7 天前
Android网络框架——OKHttp
android·java·okhttp
网络安全(华哥)8 天前
CSRF攻击&XSS攻击
okhttp·xss·csrf
不亭9 天前
python自动化测试之统一请求封装及通过文件实现接口关联
okhttp
2501_9032386512 天前
PrimeFaces Poll组件实现周期性Ajax调用
前端·ajax·okhttp·个人开发
张小勇12 天前
fetch请求总结,fastadmin中后台接口强制返回json数据
okhttp·json
ianozo17 天前
BUU17 [RoarCTF 2019]Easy Calc1
okhttp
袁震23 天前
Android-okhttp详解
android·okhttp