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


}
相关推荐
元亓亓亓2 天前
JavaWeb--day3--Ajax&Element&路由&打包部署
android·ajax·okhttp
太阳伞下的阿呆8 天前
HttpClient、OkHttp 和 WebClient
okhttp·httpclient·webclient
2503_928411568 天前
9.8 ajax+php基础语法
ajax·okhttp·php
小妖怪的夏天9 天前
react native 出现 FATAL EXCEPTION: OkHttp Dispatcher
react native·react.js·okhttp
阿华的代码王国15 天前
【Android】OkHttp发起GET请求 && POST请求
android·java·okhttp·网络连接
ahoges17 天前
easy-http类似feign的轻量级http客户端工具
java·okhttp
java_t_t20 天前
HTTP 接口调用工具类(OkHttp 版)
网络协议·http·okhttp
雨白25 天前
OkHttpClient 核心配置详解
android·okhttp
小白学大数据1 个月前
1688商品数据抓取:Python爬虫+动态页面解析
爬虫·python·okhttp