使用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);}}}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值