httpClient4.3x 使用
2016-01-05 14:23
579 查看
4.3版本简介
1、创建HTTP客户端
CloseableHttpClient client = HttpClientBuilder.create().build();
2、发送基本的GET请求
instance.execute(new HttpGet(“http://www.baidu.com”));
3、获取HTTP响应的状态码
String url = “http://www.baidu.com”; CloseableHttpResponse response = instance.execute(new HttpGet(url)); assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
4、获取响应的媒体类型
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部分
String url = “http://www.baidu.com”; CloseableHttpResponse response = instance.execute(new HttpGet(url)); String bodyAsString = EntityUtils.toString(response.getEntity()); assertThat(bodyAsString, notNullValue());
6、配置请求的超时设置
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请求
instance.execute(new HttpPost(SAMPLE_URL));
8、为HTTP请求配置重定向
CloseableHttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build(); CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL)); assertThat(reponse.getStatusLine().getStatusCode(), equalTo(301));
9、配置请求的HEADER部分
HttpGet request = new HttpGet(SAMPLE_URL); request.addHeader(HttpHeaders.ACCEPT, “application/xml”); response = instance.execute(request);
10、获取响应的HEADER部分
CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL)); Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE); assertThat(headers, not(emptyArray()));
11、关闭或释放资源
response = instance.execute(new HttpGet(SAMPLE_URL)); try{ HttpEntity entity = response.getEntity(); if(entity!=null){ InputStream instream = entity.getContent(); instream.close(); } finally{ response.close(); }
2、工具代码使用
package com.util.net; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; /** * 网络请求V3.0 * @author yanbumo */ public class Net { HttpClient client; HttpUriRequest request; HttpResponse response; private MultipartEntityBuilder multipartEntityBuilder; private Map<String, Object> params; public Net() { client = HttpClientBuilder.create().build(); } /** * 设置请求超时 * @param conTime * @param socketTime * @return */ public Net setTimeOut(int conTime,int socketTime){ RequestConfig config = RequestConfig.custom().setConnectTimeout(conTime).setSocketTimeout(socketTime).build(); setRequestConfig(config); return this; } public Net setRequestConfig(RequestConfig config){ if(request.getClass().equals(HttpGet.class)){ ((HttpGet)request).setConfig(config); }else if(request.getClass().equals(HttpPost.class)){ ((HttpPost)request).setConfig(config); } return this; } /** * GET请求 * @param url * @return */ public Net get(String url){ request = new HttpGet(url); params = new HashMap<>(); return this; } /** * POST 请求 * @param url * @return */ public Net post(String url){ request = new HttpPost(url); multipartEntityBuilder = MultipartEntityBuilder.create(); return this; } /** * 添加请求头 * @param headers * @return */ public Net addHead(Header...headers){ for (Header header : headers) { request.addHeader(header); } return this; } /** * 添加请求头 * @param name * @param value * @return */ public Net addHead(String name,Object value){ request.addHeader(name, value.toString()); return this; } /** * 添加Cookie * @param cookie * @return */ public Net addCookie(String cookie){ return addHead("Cookie", cookie); } /** * 添加参数 * @param name * @param value * @return */ public Net addParams(String name,Object value){ if(request.getClass().equals(HttpGet.class)){ addParamsGet(name, value); }else if(request.getClass().equals(HttpPost.class)){ addParamsPost(name, value); } return this; } private void addParamsGet(String name,Object value){ params.put(name, value); } private void addParamsPost(String name,Object object){ if(object.getClass().equals(File.class)){ FileBody body = new FileBody((File)object); multipartEntityBuilder.addPart(name, body); }else{ multipartEntityBuilder.addTextBody(name, object.toString()); } } /** * 执行请求 * @return */ public Net doRequest(){ try{ if(request.getClass().equals(HttpGet.class)){ doGet(); }else if(request.getClass().equals(HttpPost.class)){ doPost(); } response = client.execute bde6 (request); }catch(Exception e){ e.printStackTrace(); } return this; } private void doGet() throws URISyntaxException{ if(params.isEmpty()){ return; } String url = ""; Set<String> keys = params.keySet(); for (String key : keys) { url += "&" + key + params.get(key); } url = url.replaceFirst("&", "?"); HttpGet get = (HttpGet)request; get.setURI(new URI(get.getURI() + url)); this.request = get; } private void doPost(){ HttpPost post = (HttpPost)request; post.setEntity(multipartEntityBuilder.build()); this.request = post; } /** * 得到返回体 * @return */ public HttpResponse getResult(){ return this.response; } /** * 得到Cookie * @return */ public Header[] getCookie(){ return response.getHeaders("Set-Cookie"); } /** * 得到返回字符串 * @return */ public String getStr(){ if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ try{ return EntityUtils.toString(response.getEntity()); }catch(Exception e){ return null; } } return response.getStatusLine().getStatusCode() + ""; } /** * 下载文件 (单个文件) * @param filePath * @return */ public File getFile(String filePath){ try{ File file = new File(filePath); if(! file.exists()){ if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } file.createNewFile(); } InputStream inputStream = response.getEntity().getContent(); OutputStream outputStream = new FileOutputStream(file); int index = 0; byte[] btys = new byte[4096]; while(( index = inputStream.read( btys)) != -1){ outputStream.write( btys, 0, index); } inputStream.close(); outputStream.flush(); outputStream.close(); return file; }catch(Exception e){ return null; } } }
测试用例
Net net = new Net(); Header[] cookies = net.post("http://host:8080/user/login") .addParams("username", "username").addParams("pswd", "pswd") .doRequest().getCookie(); String rs = net.get("http://host:8080/sign/mysignpage=1&step=1000&type=1") .addHead(cookies).setTimeOut(10, 1000) .doRequest().getStr();
相关文章推荐
- ASP.NET MVC Web API HttpClient简介
- 使用httpclient实现免费的google翻译api
- PHP封装的HttpClient类用法实例
- Android 中HttpURLConnection与HttpClient使用的简单实例
- Android通过HttpURLConnection和HttpClient接口实现网络编程
- HttpClient 在Java项目中的使用详解
- 基于Java HttpClient和Htmlparser实现网络爬虫代码
- 谈谈HttpClient使用详解
- java实现HttpClient异步请求资源的方法
- 调用图灵机器人接口的问题
- Apache Client使用说明第一章(第一部分)
- volley框架下发送和读取cookie
- 浅谈HttpClient
- HttpClient不保存、发送Cookie
- HttpClient获取服务器JSON数据问题处理
- 学习 HTTP协议挺不错的一个类
- 通过Http协议下载文件、访问接口等等
- Apache HttpClient
- HttpClient 使用