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


}
相关推荐
孤客网络科技工作室13 小时前
AJAX 全面教程:从基础到高级
android·ajax·okhttp
Liknana5 天前
OKHTTP断点续传
android·okhttp·面试
爱编程的鱼9 天前
web前后端交互方式有哪些?
前端·okhttp
鞠崽2333310 天前
【六袆 - WebSocket】WebSocket的认识;一次AJAX请求模型;一次长轮询请求模型;一次WebSocket请求模型;
websocket·ajax·okhttp
吃汉堡吃到饱12 天前
【Android】浅析OkHttp(1)
android·okhttp
wa的一声哭了15 天前
黑马JavaWeb-day03
数据结构·c++·人工智能·深度学习·算法·okhttp·eclipse
小R资源15 天前
Django CSRF Token缺失或不正确
okhttp·django·csrf
我就说好玩22 天前
ajax嵌套ajax实现不刷新表单并向指定页面二次提交数据
android·ajax·okhttp
Ther23323 天前
SpringBoot中OKHttp和压缩文件的使用
okhttp
ShyTan23 天前
Java工具类--OkHttp工具类
数据库·okhttp