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


}
相关推荐
chilavert3187 天前
技术演进中的开发沉思-235 Ajax:动态数据(上)
javascript·ajax·okhttp
灰什么鱼8 天前
OkHttp + Retrofit2 调用第三方接口完整教程(以nomad为例)
java·spring boot·okhttp·retrofit
苏打水com9 天前
第六篇:Day16-18 AJAX进阶+接口对接——实现“前后端数据交互”(对标职场“接口开发”核心需求)
css·okhttp·html·js
漏洞文库-Web安全9 天前
CTFHub XSS通关:XSS-过滤关键词 - 教程
前端·安全·web安全·okhttp·网络安全·ctf·xss
chilavert31810 天前
技术演进中的开发沉思-229 Ajax:Firefox 与 Firebug
javascript·okhttp
chilavert31811 天前
技术演进中的开发沉思-224 Ajax面向对象与框架
javascript·okhttp
chilavert31811 天前
技术演进中的开发沉思-227 Ajax: Ajax 缺陷
javascript·okhttp
by__csdn12 天前
Ajax与Axios终极对比指南全方位对比解析
前端·javascript·ajax·okhttp·typescript·vue·restful
唐古乌梁海12 天前
【AJAX】AJAX详解
前端·ajax·okhttp
q***710114 天前
跨域问题解释及前后端解决方案(SpringBoot)
spring boot·后端·okhttp