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)); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性