java请求方法封装

0 阅读1分钟

 请求工具类实现

@Slf4j
public class HttpClientUtil {
    
    public static String post(String url, Map<String, String> headerMap, JSONObject body) {
        // 配置超时参数
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(20000).build();

        // 创建 HttpClient 实例
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        
         try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type","application/json");
            if (ObjectUtil.isNotEmpty(headerMap)) {
                headerMap.forEach(httpPost::setHeader);
            }
            if (ObjectUtil.isNotEmpty(body)) {

                httpPost.setEntity(
                        new StringEntity(JSONUtil.toJsonStr(body), ContentType.APPLICATION_JSON.withCharset("UTF-8")));
            }
            // 发送请求并获取响应
            CloseableHttpResponse response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity());
        }
        catch (Exception e) {
            // todo 异常处理
        }
        finally {
            closeClient(httpClient);
        }
    }

    public static String get(String url, Map<String, String> headerMap) {
        // 配置超时参数
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(20000).setSocketTimeout(20000).build();

        // 创建 HttpClient 实例
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        try {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Content-Type","application/json");
            if (ObjectUtil.isNotEmpty(headerMap)) {
                headerMap.forEach(httpGet::setHeader);
            }
            // 发送请求并获取响应
            CloseableHttpResponse response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity());
        }
        catch (Exception e) {
            // todo 异常处理
        }
        finally {
            closeClient(httpClient);
        }
    }

    private static void closeClient(CloseableHttpClient httpClient) {
        try {
            httpClient.close();
        }
        catch (IOException e) {
            log.error("关闭请求客户端资源错误,报错内容{}", e.getMessage());
        }
    }

}
           

可在接口返回后执行定制化操作如记录日志等,需要注意的是EntityUtils.toString(response.getEntity())这个方法不能执行两次,该方法本质上是解析结果流。结果可通过使用常见的json工具类进行对象构建。