HttpClient4.3 学习

来源:互联网 发布:女款羊剪绒大衣淘宝网 编辑:程序博客网 时间:2024/04/27 14:45
最近在用http协议传输,网上浏览了几个一些高手的文章,这里把他们的东西整理一下记录起来,方便自己以后复习。首先当然是 apache的官网,但是小的我e文比较烂,只能看个半懂。 http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientChunkEncodedPost.java 下面贴出来,高手写的东西和原网址 http://blog.csdn.net/chszs/article/details/16854747 一、概述 Apache HttpClient 4系列已经发布很久了,但由于它与HttpClient 3.x版本完全不兼容,以至于业内采用此库的公司较少,在互联网上也少有相关的文档资料分享。本文旨在写一个简要的Apache HttpClient 4.3开发指南,帮助开发者快速上手Apache HttpClient 4.3.x库。要注意的是,本文档中的代码在低于HttpClient 4.3版本的地方可能不能运行。二、开发手册 1、创建HTTP客户端 [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 CloseableHttpClient client = HttpClientBuilder.create().build(); 2、发送基本的GET请求 [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 instance.execute(new HttpGet(“http://www.baidu.com”)); 3、获取HTTP响应的状态码 [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 String url = “http://www.baidu.com”; CloseableHttpResponse response = instance.execute(new HttpGet(url)); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); 4、获取响应的媒体类型 [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 String url = “http://www.baidu.com”; CloseableHttpResponse response = instance.execute(new HttpGet(url)); String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType(); assertThat(contentMimeType, equalTo(ContentType.TEXT_HTML.getMimeType())); 5、获取响应的BODY部分 [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 String url = “http://www.baidu.com”; CloseableHttpResponse response = instance.execute(new HttpGet(url)); String bodyAsString = EntityUtils.toString(response.getEntity()); assertThat(bodyAsString, notNullValue()); 6、配置请求的超时设置 [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 @Test(expected=SocketTimeoutException.class) public void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws ClientProtocolException, IOException{ RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(50).setConnectTimeout(50) .setSocketTimeout(50).build(); HttpGet request = new HttpGet(SAMPLE_URL); request.setConfig(requestConfig); instance.execute(request); } 7、发送POST请求 [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 instance.execute(new HttpPost(SAMPLE_URL)); 8、为HTTP请求配置重定向 [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 CloseableHttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build(); CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL)); assertThat(reponse.getStatusLine().getStatusCode(), equalTo(301)); 9、配置请求的HEADER部分 [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 HttpGet request = new HttpGet(SAMPLE_URL); request.addHeader(HttpHeaders.ACCEPT, “application/xml”); response = instance.execute(request); 10、获取响应的HEADER部分 [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL)); Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE); assertThat(headers, not(emptyArray())); 11、关闭或释放资源 [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 response = instance.execute(new HttpGet(SAMPLE_URL)); try{ HttpEntity entity = response.getEntity(); if(entity!=null){ InputStream instream = entity.getContent(); instream.close(); } } finally{ response.close(); } 还有一个高手的: 1.需要的jar包 httpClient下载 2.使用示例: [java] view plaincopy在CODE上查看代码片派生到我的代码片 /** * * 方法说明:使用百度place v2.0 采集位置坐标 * @author admin 2013-12-11 上午08:39:45 * @param houses : 位置名称 * @param city : 城市 * @return */ public PlaceResultData pickup(String houses,String city){ CloseableHttpClient client = null; PlaceResultData data = null; try { String housesTo = URLEncoder.encode(houses, "UTF-8"); String regionTo = URLEncoder.encode(city, "UTF-8"); String url = "http://api.map.baidu.com/place/v2/search?ak="自己的key"&output=json&query=" + housesTo+ "&page_size=1&page_num=0&scope=1®ion=" + regionTo; client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//设置请求和传输超时时间 httpPost.setConfig(requestConfig); HttpResponse response = client.execute(httpPost); HttpEntity entity = response.getEntity(); if (entity != null) { String json = EntityUtils.toString(entity, "UTF-8"); ObjectMapper mapper = new ObjectMapper(); data = mapper.readValue(json, PlaceResultData.class); } } catch (UnsupportedEncodingException e) { logger.error(e); } catch (ConnectTimeoutException e) { System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println("连接超时 位置名称:" + houses); System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++"); data = pickup(houses, city); logger.error("连接超时 位置:" + houses); } catch (SocketTimeoutException e) { System.out.println("》》》》》》》》》》》》》》》》》》》》》》》》》》》"); System.out.println("网络异常 位置名称:" + houses); System.out.println("》》》》》》》》》》》》》》》》》》》》》》》》》》》"); data = pickup(houses, city); logger.error("网络异常 位置名称:" + houses); }catch (UnrecognizedPropertyException e) { System.out.println("-------------------------------------------------"); System.out.println("转换json数据失败的位置:" + houses); System.out.println("-------------------------------------------------"); logger.error("转换json数据失败的位置:" + houses); } catch (EOFException e) { System.out.println("**************************************************"); System.out.println("EOFException异常 位置名称:" + houses); System.out.println("**************************************************"); data = pickup(houses, city); logger.error("EOFException异常:" + e); } catch (IOException e) { System.out.println("《《《《《《《《《《《《《《《《《《《《《《《《《《《"); System.out.println("IO异常 位置名称:" + houses); System.out.println("《《《《《《《《《《《《《《《《《《《《《《《《《《《"); logger.error("IO异常:" + e); } finally{ try { client.close(); } catch (IOException e) { logger.error(e); } } return data; } 注:此示例方法中涉级到的jar包除了httpClient的包,还有 jackson.jar log4j.jar 其中的关联jar包我这里就不列出来了
0 0