httpclient4.3.x模拟post及get请求

在web开发中,我们经常需要模拟post及get请求,现在网上比较多的是使用httpclient3.x,然而httpclient4.x已经发布好几年了,而且4.x之后改名为HttpComponents,显然是今后的趋势.
Apache HttpComponents4.x中的HttpClient是一个很好的工具,它符合HTTP1.1规范,是基于HttpCore类包的实现。但是HttpComponents4.x较之前httpclient3.x的API变化比较大,已经分为HttpClient,HttpCore,HttpAsyncClient等多个组件,在模拟post及get请求时的编码也出现了较大的变化.

下面是httpclient4.3.4模拟get请求的例程
public void requestGet(String urlWithParams) throws Exception {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        
        //HttpGet httpget = new HttpGet("http://www.baidu.com/");
        HttpGet httpget = new HttpGet(urlWithParams);   

        //配置请求的超时设置
        RequestConfig requestConfig = RequestConfig.custom()  
                .setConnectionRequestTimeout(50)
                .setConnectTimeout(50)  
                .setSocketTimeout(50).build();  
        httpget.setConfig(requestConfig);
        
        CloseableHttpResponse response = httpclient.execute(httpget);        
        System.out.println("StatusCode -> " + response.getStatusLine().getStatusCode());
        
        HttpEntity entity = response.getEntity();        
        String jsonStr = EntityUtils.toString(entity);//, "utf-8");
        System.out.println(jsonStr);
        
        httpget.releaseConnection();
}

httpclient4.3.4模拟post请求的例程
public void requestPost(String url,List<NameValuePair> params) throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        
    HttpPost httppost = new HttpPost(url);
        httppost.setEntity(new UrlEncodedFormEntity(params));
        
        CloseableHttpResponse response = httpclient.execute(httppost);
        System.out.println(response.toString());
        
        HttpEntity entity = response.getEntity();
        String jsonStr = EntityUtils.toString(entity, "utf-8");
        System.out.println(jsonStr);
        
        httppost.releaseConnection();
}

运行post方法时,可以
public static void main(String[] args){
    try {
        String loginUrl = "http://localhost:8080/yours";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", "zhang"));
        params.add(new BasicNameValuePair("passwd", "123"));
            
        requestPost(loginUrl,params);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

最后给出httpcomponents官网的例程
http://hc.apache.org/httpcomponents-core-4.3.x/examples.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值