Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增长了易用性和灵活性(具体区别,往后咱们再讨论),它不只是客户端发送Http请求变得容易,并且也方便了开发人员测试接口(基于Http协议的),即提升了开发的效率,也方便提升代码的健壮性。所以熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深刻。java
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,而且它支持HTTP协议最新的版本和建议。HttpClient已经应用在不少的项目中,好比Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。apache
下载地址: http://hc.apache.org/downloads.cgi编程
1. 基于标准、纯净的Java语言。实现了Http1.0和Http1.1服务器
2. 以可扩展的面向对象的结构实现了Http所有的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。多线程
3. 支持HTTPS协议。app
4. 经过Http代理创建透明的链接。socket
5. 利用CONNECT方法经过Http代理创建隧道的https链接。ide
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。工具
7. 插件式的自定义认证方案。post
8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。
9. 链接管理器支持多线程应用。支持设置最大链接数,同时支持设置每一个主机的最大链接数,发现并关闭过时的链接。
10. 自动处理Set-Cookie中的Cookie。
11. 插件式的自定义Cookie策略。
12. Request的输出流能够避免流中内容直接缓冲到socket服务器。
13. Response的输入流能够有效的从socket服务器直接读取相应内容。
14. 在http1.0和http1.1中利用KeepAlive保持持久链接。
15. 直接获取服务器发送的response code和 headers。
16. 设置链接超时的能力。
17. 实验性的支持http1.1 response caching。
18. 源代码基于Apache License 可免费获取。
使用HttpClient发送请求、接收响应很简单,通常须要以下几步便可。
1. 建立HttpClient对象。
2. 建立请求方法的实例,并指定请求URL。若是须要发送GET请求,建立HttpGet对象;若是须要发送POST请求,建立HttpPost对象。
3. 若是须要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可经过该对象获取服务器的响应内容。
6. 释放链接。不管执行方法是否成功,都必须释放链接
所需JAR
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
package cn.com.demo; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.util.PublicSuffixMatcher; import org.apache.http.conn.util.PublicSuffixMatcherLoader; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpClientUtil { private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000) .setConnectionRequestTimeout(15000).build(); // 单例模式 private static HttpClientUtil instance = null; private HttpClientUtil() { } public static HttpClientUtil getInstance() { if (instance == null) { instance = new HttpClientUtil(); } return instance; } /** * 发送 post请求 * * @param httpUrl * 地址 */ public String sendHttpPost(String httpUrl) { HttpPost httpPost = new HttpPost(httpUrl);// 建立httpPost return sendHttpPost(httpPost); } /** * 发送 post请求 * * @param httpUrl * 地址 * @param params * 参数(格式:key1=value1&key2=value2) */ public String sendHttpPost(String httpUrl, String params) { HttpPost httpPost = new HttpPost(httpUrl); try { StringEntity stringEntity = new StringEntity(params, "UTF-9=8"); stringEntity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(stringEntity); } catch (Exception e) { e.printStackTrace(); } return sendHttpPost(httpPost); } /** * 发送 post请求 * * @param httpUrl * 地址 * @param maps * 参数 */ public String sendHttpPost(String httpUrl, Map<String, String> maps) { HttpPost httpPost = new HttpPost(httpUrl); // 建立参数队列 List<NameValuePair> nameValuePairs = new ArrayList<>(); for (String key : maps.keySet()) { nameValuePairs.add(new BasicNameValuePair(key, maps.get(key))); } try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); } catch (Exception e) { e.printStackTrace(); } return sendHttpPost(httpPost); } /** * 发送 post请求(带文件) * * @param httpUrl * 地址 * @param maps * 参数 * @param fileLists * 附件 */ public String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) { HttpPost httpPost = new HttpPost(httpUrl); MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create(); for (String key : maps.keySet()) { meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN)); } for (File file : fileLists) { FileBody fileBody = new FileBody(file); meBuilder.addPart("files", fileBody); } HttpEntity reqEntity = meBuilder.build(); httpPost.setEntity(reqEntity); return sendHttpPost(httpPost); } /** * 发送Post请求 * * @param httpPost * @return */ private String sendHttpPost(HttpPost httpPost) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try { // 建立默认的httpClient实例 httpClient = HttpClients.createDefault(); httpPost.setConfig(requestConfig); // 执行请求 response = httpClient.execute(httpPost); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return responseContent; } /** * 发送 get请求 * * @param httpUrl */ public String sendHttpGet(String httpUrl) { HttpGet httpGet = new HttpGet(httpUrl); return sendHttpGet(httpGet); } /** * 发送 get请求Https * * @param httpUrl */ public String sendHttpsGet(String httpUrl) { HttpGet httpGet = new HttpGet(httpUrl); return sendHttpGet(httpGet); } /** * 发送Get请求 * * @param httpPost * @return */ public String sendHttpGet(HttpGet httpGet) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try { // 建立默认的httpClient实例 httpClient = HttpClients.createDefault(); httpGet.setConfig(requestConfig); // 执行请求 response = httpClient.execute(httpGet); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return responseContent; } /** * 发送Get请求Https * * @param httpPost * @return */ private String sendHttpsGet(HttpGet httpGet) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try { // 建立默认的httpClient实例 PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader .load(new URL(httpGet.getURI().toString())); DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher); httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build(); httpGet.setConfig(requestConfig); // 执行请求 response = httpClient.execute(httpGet); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return responseContent; } }
package cn.com.demo; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; public class HttpClientUtilTest { @Test public void testSendHttpPost1() { String responseContent = HttpClientUtil.getInstance() .sendHttpPost("http://192.168.1.83:9090/manage!login?phone=1&password=1"); System.out.println("response Content" + responseContent); } @Test public void testSendHttpPost2() { String responseContent = HttpClientUtil.getInstance().sendHttpPost("http://localhost:8089/test/send", "username=test01&password=123456"); System.out.println("reponse content:" + responseContent); } @Test public void testSendHttpPost3() { Map<String, String> maps = new HashMap<String, String>(); maps.put("username", "test01"); maps.put("password", "123456"); String responseContent = HttpClientUtil.getInstance().sendHttpPost("http://localhost:8089/test/send", maps); System.out.println("reponse content:" + responseContent); } @Test public void testSendHttpPost4() { Map<String, String> maps = new HashMap<String, String>(); maps.put("username", "test01"); maps.put("password", "123456"); List<File> fileLists = new ArrayList<File>(); fileLists.add(new File("D://test//httpclient//1.png")); fileLists.add(new File("D://test//httpclient//1.txt")); String responseContent = HttpClientUtil.getInstance().sendHttpPost("http://localhost:8089/test/sendpost/file", maps, fileLists); System.out.println("reponse content:" + responseContent); } @Test public void testSendHttpGet() { String responseContent = HttpClientUtil.getInstance() .sendHttpGet("http://localhost:8089/test/send?username=test01&password=123456"); System.out.println("reponse content:" + responseContent); } @Test public void testSendHttpsGet() { String responseContent = HttpClientUtil.getInstance().sendHttpsGet("https://www.baidu.com"); System.out.println("reponse content:" + responseContent); } }