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


}
相关推荐
知月玄1 天前
网页前端开发(基础进阶4--axios)
okhttp
余渔鱼11232 天前
ajax学习手册
学习·ajax·okhttp
smallluan3 天前
入门AJAX——XMLHttpRequest(Post)
前端·ajax·okhttp
志存高远665 天前
(面试)OkHttp实现原理
okhttp
隐-梵6 天前
Android studio进阶开发(七)---做一个完整的登录系统(前后端连接)
android·数据库·ide·spring·okhttp·android studio
隐-梵12 天前
Android studio进阶开发(六)--如何用真机通过okhttp连接服务器
服务器·数据库·okhttp·android studio
每次的天空13 天前
Android-OkHttp与Retrofit学习总结
android·okhttp·retrofit
tmacfrank13 天前
Android 网络全栈攻略(四)—— 从 OkHttp 拦截器来看 HTTP 协议一
android·网络·okhttp
tmacfrank15 天前
Android 网络全栈攻略(五)—— 从 OkHttp 拦截器来看 HTTP 协议二
android·网络·okhttp
酷爱码15 天前
jQuery Ajax中dataType 和 content-type 参数的作用详解
ajax·okhttp·jquery