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 天前
Android学习总结之OKHttp拦截器和缓存
android·学习·okhttp
东方芷兰4 天前
JavaWeb 课堂笔记 —— 04 Ajax
笔记·ajax·okhttp
隔壁小查6 天前
【后端开发】初识Spring IoC与SpringDI、图书管理系统
java·spring·okhttp
quo-te6 天前
AJAX简介
前端·ajax·okhttp
seabirdssss13 天前
通过动态获取项目的上下文路径来确保请求的 URL 兼容两种启动方式(IDEA 启动和 Tomcat 部署)下都能正确解析
java·okhttp·tomcat·intellij-idea
ps酷教程13 天前
Apache httpclient & okhttp(2)
okhttp·apache
Code额13 天前
认识 Promise
okhttp·promise
ps酷教程15 天前
OkHttp&HttpClient
okhttp·httpclient
东东__net19 天前
27_promise
okhttp
阿湯哥19 天前
SSE SseEmitter.completeWithError(e) 触发的处理逻辑
okhttp