OkHttp3.8.1版 工具类

import com.alibaba.fastjson.JSON;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpUtil {

    private static final OkHttpClient httpClient = new OkHttpClient()
            .newBuilder().writeTimeout(1, TimeUnit.MINUTES)
            .readTimeout(1, TimeUnit.MINUTES)
            .connectTimeout(30, TimeUnit.SECONDS).build();

    private static final MediaType jsonMediaType = MediaType.parse("application/json;charset=UTF-8");

    private static Headers toHeader(Map<String, String> header) {
        if(header == null) {
            return Headers.of();
        }
        return Headers.of(header);
    }

    public static Response getToResponse(String url, Map<String, String> param, Map<String, String> header) throws IOException {
        Request request;
        Request.Builder requestBuilder = new Request.Builder().headers(toHeader(header));
        if(param != null) {
            HttpUrl httpUrl = HttpUrl.parse(url);
            if(httpUrl == null) {
                throw new RuntimeException("request url error: " + url);
            }
            HttpUrl.Builder urlBuilder = httpUrl.newBuilder();
            param.forEach(urlBuilder::addQueryParameter);
            request = requestBuilder.url(urlBuilder.build()).build();
        } else {
            request = requestBuilder.url(url).build();
        }
        Call r = httpClient.newCall(request);
        return r.execute();
    }

    public static Response postToResponse(String url, Object param, Map<String, String> header) throws IOException {
        Request request = new Request.Builder().url(url).headers(toHeader(header))
                .post(RequestBody.create(jsonMediaType, param instanceof String ? (String) param :
                        JSON.toJSONString(param))).build();
        Call r = httpClient.newCall(request);
        return r.execute();
    }

    public static Response postToResponseByForm(String url, Map<String, String> param, Map<String, String> header) throws IOException {
        FormBody.Builder build = new FormBody.Builder();
        param.forEach(build::add);
        Request request = new Request.Builder().url(url).headers(toHeader(header))
                .post(build.build()).build();
        Call r = httpClient.newCall(request);
        return r.execute();
    }

    public static String getByRest(String url) throws IOException {
        ResponseBody body = getToResponse(url, null, null).body();
        return body != null ? body.string() : null;
    }

    public static String getByRest(String url, Map<String, String> param) throws IOException {
        ResponseBody body = getToResponse(url, param, null).body();
        return body != null ? body.string() : null;
    }

    public static String getByRest(String url, Map<String, String> param, Map<String, String> header) throws IOException {
        ResponseBody body = getToResponse(url, param, header).body();
        return body != null ? body.string() : null;
    }

    public static String postByRest(String url) throws IOException {
        ResponseBody body = postToResponse(url, null, null).body();
        return body != null ? body.string() : null;
    }

    public static String postByRest(String url, Object param) throws IOException {
        ResponseBody body = postToResponse(url, param, null).body();
        return body != null ? body.string() : null;
    }

    public static String postByForm(String url, Map<String, String> param) throws IOException {
        ResponseBody body = postToResponseByForm(url, param, null).body();
        return body != null ? body.string() : null;
    }

    public static String postByRest(String url, Object param, Map<String, String> header) throws IOException {
        ResponseBody body = postToResponse(url, param, header).body();
        return body != null ? body.string() : null;
    }

    public static String postByForm(String url, Map<String, String> param, Map<String, String> header) throws IOException {
        ResponseBody body = postToResponseByForm(url, param, header).body();
        return body != null ? body.string() : null;
    }
}

 加上日志

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.Buffer;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class OkHttpUtilClient {

    private static ThreadLocal<Long> time = new ThreadLocal<>();

    private static final okhttp3.OkHttpClient httpClient = new OkHttpClient()
            .newBuilder().readTimeout(1, TimeUnit.MINUTES)
            .writeTimeout(1, TimeUnit.MINUTES)
            .connectTimeout(30, TimeUnit.SECONDS)
            .eventListenerFactory(a -> new EventListener() {
                @Override
                public void callStart(Call call) {
                    log.info("OkHttpCallStart: " + requestToString(call.request()));
                    time.set(System.currentTimeMillis());
                }
                @Override
                public void callEnd(Call call) {
                    Long t = time.get();
                    log.info("OkHttpCallEnd: " + call.request().toString() + (t != null ?
                            " , OKHttp耗时: " + (System.currentTimeMillis() - t) : ""));
                    time.remove();
                }
            }).build();

    private static String requestToString(Request request) {
        return "okHttpRequest: " + request.toString() +
                " header: " + request.headers().toString().replace("\n", " ") +
                " body: " + bodyToString(request);
    }

    private static String bodyToString(final Request request){
        try {
            Request copy = request.newBuilder().build();
            if(copy.body() == null) {
                return "";
            }
            Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final Exception e) {
            return "";
        }
    }

    private static final MediaType jsonMediaType = MediaType.parse("application/json;charset=UTF-8");

    private static Headers toHeader(Map<String, String> header) {
        if(header == null) {
            return Headers.of();
        }
        return Headers.of(header);
    }

    private static String responseToString(Response r) throws IOException {
        ResponseBody body = r.body();
        String result = body != null ? body.string() : null;
        log.info("OkHttpCallResult: " + result + " request: " + requestToString(r.request()));
        return result;
    }

    public static Response getToResponse(String url, Map<String, String> param, Map<String, String> header) throws IOException {
        Request request;
        Request.Builder requestBuilder = new Request.Builder().headers(toHeader(header));
        if(param != null) {
            HttpUrl httpUrl = HttpUrl.parse(url);
            if(httpUrl == null) {
                throw new RuntimeException("request url error: " + url);
            }
            HttpUrl.Builder urlBuilder = httpUrl.newBuilder();
            param.forEach(urlBuilder::addQueryParameter);
            request = requestBuilder.url(urlBuilder.build()).build();
        } else {
            request = requestBuilder.url(url).build();
        }
        Call r = httpClient.newCall(request);
        return r.execute();
    }

    public static Response postToResponse(String url, Object param, Map<String, String> header) throws IOException {
        Request request = new Request.Builder().url(url).headers(toHeader(header))
                .post(RequestBody.create(jsonMediaType, param instanceof String ? (String) param :
                        JSON.toJSONString(param))).build();
        Call r = httpClient.newCall(request);
        return r.execute();
    }

    public static Response postToResponseByForm(String url, Map<String, String> param, Map<String, String> header) throws IOException {
        FormBody.Builder build = new FormBody.Builder();
        param.forEach(build::add);
        Request request = new Request.Builder().url(url).headers(toHeader(header))
                .post(build.build()).build();
        Call r = httpClient.newCall(request);
        return r.execute();
    }

    public static String getByRest(String url) throws IOException {
        return responseToString(getToResponse(url, null, null));
    }

    public static String getByRest(String url, Map<String, String> param) throws IOException {
        return responseToString(getToResponse(url, param, null));
    }

    public static String getByRest(String url, Map<String, String> param, Map<String, String> header) throws IOException {
        return responseToString(getToResponse(url, param, header));
    }

    public static String postByRest(String url) throws IOException {
        return responseToString(postToResponse(url, null, null));
    }

    public static String postByRest(String url, Object param) throws IOException {
        return responseToString(postToResponse(url, param, null));
    }

    public static String postByForm(String url, Map<String, String> param) throws IOException {
        return responseToString(postToResponseByForm(url, param, null));
    }

    public static String postByRest(String url, Object param, Map<String, String> header) throws IOException {
        return responseToString(postToResponse(url, param, header));
    }

    public static String postByForm(String url, Map<String, String> param, Map<String, String> header) throws IOException {
        return responseToString(postToResponseByForm(url, param, header));
    }
}

 

posted @ 2022-07-20 16:12  数学与IT  阅读(398)  评论(0编辑  收藏  举报