1. /**
    2. * OkHttp 工具类
    3. */
    4. @Slf4j
    5. public class OkHttpUtil {
    6. private OkHttpUtil() {
    7. }
    8. //////////////////////////////////////////////////////////////////////////
    9. // OkHttpClient Singleton
    10. //////////////////////////////////////////////////////////////////////////
    11. public static OkHttpClient getOKHttpClientInstance() {
    12. return LazyLoad.client;
    13. }
    14. private static class LazyLoad {
    15. private static final OkHttpClient client = new OkHttpClient();
    16. }
    17. //////////////////////////////////////////////////////////////////////////
    18. // util method
    19. //////////////////////////////////////////////////////////////////////////
    20. /**
    21. * <h2>执行post请求,注意要求目标接口返回响应头具有application/json </h2>
    22. *
    23. * @param url 请求地址
    24. * @param param 携带的参数实体类
    25. * @param headersParam 请求头参数
    26. * @param <T> 实体类类型
    27. * @return {@link Response} 响应
    28. * @throws IOException 执行请求时可能出现的异常
    29. */
    30. public static <T> Response doPost(String url, T param, Map<String, String> headersParam) throws IOException {
    31. MediaType contentType = MediaType.get(org.springframework.http.MediaType.APPLICATION_JSON_VALUE);
    32. RequestBody requestBody = RequestBody.create(JSON.toJSONString(param), contentType);
    33. // 构建 headers
    34. Headers headers = _buildHeaders(headersParam);
    35. // 构建 request
    36. Request request = new Request.Builder()
    37. .headers(headers)
    38. .url(url)
    39. .post(requestBody)
    40. .build();
    41. // 执行请求, 直接返回即可
    42. return getOKHttpClientInstance().newCall(request).execute();
    43. // sb了, 居然直接关掉流了。导致出现了 java.lang.IllegalStateException: closed
    44. // try (Response response = getOKHttpClientInstance().newCall(request).execute()) {
    45. // return response;
    46. // } catch (IOException e) {
    47. // log.error("请求url: {}时候发生了错误: {}", url, e.getLocalizedMessage(), e);
    48. // throw e;
    49. // }
    50. }
    51. /**
    52. * 填充 header 为 headers
    53. *
    54. * @param headersParam {@link Map} headers 头
    55. * @return {@link Headers} okHttp 的 headers 头
    56. */
    57. private static Headers _buildHeaders(Map<String, String> headersParam) {
    58. Headers.Builder headerBuilder = new Headers.Builder();
    59. for (Map.Entry<String, String> entry : headersParam.entrySet()) {
    60. headerBuilder.add(entry.getKey(), entry.getValue());
    61. }
    62. return headerBuilder.build();
    63. }
    64. }