使用CloseableHttpClient 模拟发送HttpGet和HttpPost请求

项目中经常会用到模拟Http请求,而jdk 下的 rt.jar核心库中也有 java.net提供了这方面的功能,但是总体而言,功能还是缺少灵活性和全面性,HttpClient的出现就是弥补了其缺失的功能。HttpClient不是浏览器客户端,而是一个客户端和服务端实现通信的Http组件库。本篇文章主要讲解CloseableHttpClient 的使用。

1. 项目中添加依赖的jar包

   

2. 上代码,代码中详细介绍每个部分的作用

2.1 模拟HttpGet请求 

/**
 * 模拟HttpGet 请求
 * @param url
 * @return
 */
public static String HttpGet(String url){
    //单位毫秒
    RequestConfig requestConfig = RequestConfig.custom()
        .setConnectionRequestTimeout(3000).setConnectTimeout(3000)
        .setSocketTimeout(3000).build();//设置请求的状态参数

    CloseableHttpClient httpclient = HttpClients.createDefault();//创建 CloseableHttpClient 
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);

    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpGet);//返回请求执行结果
        int statusCode = response.getStatusLine().getStatusCode();//获取返回的状态值
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        } else {
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
            return result;
        }
    } catch (Exception e) {
        logger.error("httpget Exception handle-- > " + e);
    } finally {
        if (response != null){
            try {
                response.close();//关闭response
            } catch (IOException e) {
                logger.error("httpget IOException handle-- > " + e);
            }
        }
        if(httpclient != null){
            try {
                httpclient.close();//关闭httpclient
            } catch (IOException e) {
                logger.error("httpget IOException handle-- > " + e);
            }
        }
    }
    return null;
}

2.2 模拟HttpPost请求

/**
 * 模拟HttpPost请求
 * @param url
 * @param jsonString
 * @return
 */
public static String HttpPost(String url, String jsonString){
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();//创建CloseableHttpClient
    HttpPost httpPost = new HttpPost(url);//实现HttpPost
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
    httpPost.setConfig(requestConfig); //设置httpPost的状态参数
    httpPost.addHeader("Content-Type", "application/json");//设置httpPost的请求头中的MIME类型为json
    StringEntity requestEntity = new StringEntity(jsonString, "utf-8");
    httpPost.setEntity(requestEntity);//设置请求体
    try {
        response = httpClient.execute(httpPost, new BasicHttpContext());//执行请求返回结果
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            return null;
        }
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String resultStr = EntityUtils.toString(entity, "utf-8");
            return resultStr;
        } else {
            return null;
        }
    } catch (Exception e) {
        logger.error("httpPost method exception handle-- > " + e);
        return null;
    } finally {
        if (response != null){
            try {
                response.close();//最后关闭response
            } catch (IOException e) {
                logger.error("httpPost method IOException handle -- > " + e);
            }
        }if(httpClient != null){try {httpClient.close();} catch (IOException e) {logger.error("httpPost method exception handle-- > " + e);}}}}

猜你喜欢

转载自blog.csdn.net/t2080305/article/details/80551855
今日推荐