【HttpClient4】 基本操作

1、创建HTTP客户端
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. CloseableHttpClient client = HttpClientBuilder.create().build();  

2、发送基本的GET请求
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. instance.execute(new HttpGet(“http://www.baidu.com”));  

3、获取HTTP响应的状态码
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. String url = “http://www.baidu.com”;  
  2. CloseableHttpResponse response = instance.execute(new HttpGet(url));  
  3. assertThat(response.getStatusLine().getStatusCode(), equalTo(200));  

4、获取响应的媒体类型
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. String url = “http://www.baidu.com”;  
  2. CloseableHttpResponse response = instance.execute(new HttpGet(url));  
  3. String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();  
  4. assertThat(contentMimeType, equalTo(ContentType.TEXT_HTML.getMimeType()));  

5、获取响应的BODY部分
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. String url = “http://www.baidu.com”;  
  2. CloseableHttpResponse response = instance.execute(new HttpGet(url));  
  3. String bodyAsString = EntityUtils.toString(response.getEntity());  
  4. assertThat(bodyAsString, notNullValue());  

6、配置请求的超时设置
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. @Test(expected=SocketTimeoutException.class)  
  2. public void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws ClientProtocolException, IOException{  
  3.     RequestConfig requestConfig = RequestConfig.custom()  
  4.     .setConnectionRequestTimeout(50).setConnectTimeout(50)  
  5.     .setSocketTimeout(50).build();  
  6.     HttpGet request = new HttpGet(SAMPLE_URL);  
  7.     request.setConfig(requestConfig);  
  8.     instance.execute(request);  
  9. }  

7、发送POST请求
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. instance.execute(new HttpPost(SAMPLE_URL));  

8、为HTTP请求配置重定向
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. CloseableHttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build();  
  2. CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL));  
  3. assertThat(reponse.getStatusLine().getStatusCode(), equalTo(301));  

9、配置请求的HEADER部分
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. HttpGet request = new HttpGet(SAMPLE_URL);  
  2. request.addHeader(HttpHeaders.ACCEPT, “application/xml”);  
  3. response = instance.execute(request);  

10、获取响应的HEADER部分
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL));  
  2. Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);  
  3. assertThat(headers, not(emptyArray()));  

11、关闭或释放资源
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. response = instance.execute(new HttpGet(SAMPLE_URL));  
  2. try{  
  3.   HttpEntity entity = response.getEntity();  
  4.   if(entity!=null){  
  5. InputStream instream = entity.getContent();  
  6. instream.close();  
  7.   }  
  8. finally{  
  9.   response.close();  
  10. }  

12 URI构造器

            URI uri = new URIBuilder().setScheme("http")
                                      .setHost("www.baidu.com")
                                      .setPath("wenku")
                                      .setParameter("name", "xiyouji")
                                      .setParameter("author", "wuchengen").build();

            System.out.println(uri);   // 结果为http://www.baidu.comwenku?name=xiyouji&author=wuchengen

13 FORM参数

        List<NameValuePair> formParamList = new ArrayList<NameValuePair>();
        formParamList.add(new BasicNameValuePair("name", "zhangsan"));
        formParamList.add(new BasicNameValuePair("age", "20"));
        
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParamList);
        
        HttpPost post = new HttpPost();
        post.setEntity(formEntity);

14 String消息体

        StringEntity stringEntity = new StringEntity("{\"name\":\"fabregas\"}");
        StringEntity stringEntity2 = new StringEntity("{\"name\":\"fabregas\"}", ContentType.APPLICATION_JSON);
        StringEntity stringEntity3 = new StringEntity("{\"name\":\"fabregas\"}", Consts.UTF_8);
        
        StringEntity stringEntity4 = new StringEntity("{\"name\":\"fabregas\"}", ContentType.create("application/json", "UTF-8"));
        
        StringEntity stringEntity5 = new StringEntity("{\"name\":\"fabregas\"}", ContentType.APPLICATION_JSON.withCharset(Consts.UTF_8));
 
15 连接池

        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();

        connManager.setMaxTotal(200);
        connManager.setDefaultMaxPerRoute(10);

        CloseableHttpClient client = HttpClients.custom()
                .setConnectionManager(connManager).build();






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值