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


}
相关推荐
Amumu1213818 小时前
React 前端请求
前端·react.js·okhttp
38242782719 小时前
JS表单提交:submit事件的关键技巧与注意事项
前端·javascript·okhttp
小猪配偶儿_oaken5 天前
SpringBoot实现单号生成功能(Java&若依)
java·spring boot·okhttp
雨雨雨雨雨别下啦5 天前
ajax和axios到底是什么
前端·ajax·okhttp
莓有烦恼吖6 天前
基于AI图像识别与智能推荐的校园食堂评价系统研究 06-文件上传模块
android·okhttp
源远流长jerry6 天前
浏览器的同源策略
服务器·http·okhttp
粤M温同学7 天前
Android OkHttp 下载限速方案实现
android·okhttp
qq_4061761414 天前
JavaScript的同步与异步
前端·网络·tcp/ip·ajax·okhttp
A242073493016 天前
深入浅出理解AJAX:核心原理与POST/GET区别详解
前端·ajax·okhttp
吃喝不愁霸王餐APP开发者17 天前
使用OkHttp连接池优化高频调用美团API的网络资源复用效率
okhttp