Apache HttpClient使用详解

2024-09-08 12:32

本文主要是介绍Apache HttpClient使用详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

转载地址:http://eksliang.iteye.com/blog/2191017


Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。

 

一、简介

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

 

二、特性

1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1

2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。

3. 支持HTTPS协议。

4. 通过Http代理建立透明的连接。

5. 利用CONNECT方法通过Http代理建立隧道的https连接。

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。

7. 插件式的自定义认证方案。

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 可免费获取

 

三、使用方法

       Mavn坐标

Java代码   收藏代码
  1. <dependency>  
  2.     <groupId>org.apache.httpcomponents</groupId>  
  3.     <artifactId>httpclient</artifactId>  
  4.     <version>4.3.4</version>  
  5. </dependency>  

 

使用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. 释放连接。无论执行方法是否成功,都必须释放连接

 

 

四.post跟get请求示例
Java代码   收藏代码
  1. package com.ickes;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import org.apache.http.HttpEntity;  
  6. import org.apache.http.NameValuePair;  
  7. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  8. import org.apache.http.client.methods.CloseableHttpResponse;  
  9. import org.apache.http.client.methods.HttpGet;  
  10. import org.apache.http.client.methods.HttpPost;  
  11. import org.apache.http.entity.StringEntity;  
  12. import org.apache.http.impl.client.CloseableHttpClient;  
  13. import org.apache.http.impl.client.HttpClients;  
  14. import org.apache.http.message.BasicNameValuePair;  
  15. import org.apache.http.protocol.HTTP;  
  16. import org.apache.http.util.EntityUtils;  
  17.   
  18. public class HttpClientDemo {  
  19.       
  20.     public static void main(String[] args) throws Exception  {   
  21.         get();  
  22.     }  
  23.       
  24.     /** 
  25.      * post方式提交json代码 
  26.      * @throws Exception  
  27.      */  
  28.     public static void postJson() throws Exception{  
  29.         //创建默认的httpClient实例.   
  30.         CloseableHttpClient httpclient = null;  
  31.         //接收响应结果  
  32.         CloseableHttpResponse response = null;  
  33.         try {  
  34.             //创建httppost  
  35.             httpclient = HttpClients.createDefault();    
  36.             String url ="http://192.168.16.36:8081/goSearch/gosuncn/deleteDocs.htm";  
  37.             HttpPost httpPost = new HttpPost(url);  
  38.             httpPost.addHeader(HTTP.CONTENT_TYPE,"application/x-www-form-urlencoded");  
  39.             //参数  
  40.             String json ="{'ids':['html1','html2']}";  
  41.             StringEntity se = new StringEntity(json);  
  42.             se.setContentEncoding("UTF-8");  
  43.             se.setContentType("application/json");//发送json需要设置contentType  
  44.             httpPost.setEntity(se);  
  45.             response = httpclient.execute(httpPost);  
  46.             //解析返结果  
  47.             HttpEntity entity = response.getEntity();   
  48.             if(entity != null){  
  49.                 String resStr = EntityUtils.toString(entity, "UTF-8");      
  50.                 System.out.println(resStr);  
  51.             }  
  52.         } catch (Exception e) {  
  53.             throw e;  
  54.         }finally{  
  55.             httpclient.close();  
  56.             response.close();  
  57.         }  
  58.     }  
  59.       
  60.      /**  
  61.      * post方式提交表单(模拟用户登录请求)  
  62.      * @throws Exception  
  63.      */    
  64.     public static void postForm() throws Exception  {    
  65.         // 创建默认的httpClient实例.      
  66.         CloseableHttpClient httpclient = null;  
  67.         //发送请求  
  68.         CloseableHttpResponse response = null;  
  69.         try {  
  70.             httpclient = HttpClients.createDefault();    
  71.             // 创建httppost      
  72.             String url= "http://localhost:8080/search/ajx/user.htm";  
  73.             HttpPost httppost = new HttpPost(url);    
  74.             // 创建参数队列      
  75.             List<NameValuePair> formparams = new ArrayList<NameValuePair>();    
  76.             formparams.add(new BasicNameValuePair("username""admin"));    
  77.             formparams.add(new BasicNameValuePair("password""123456"));  
  78.             //参数转码  
  79.             UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");    
  80.             httppost.setEntity(uefEntity);   
  81.             response = httpclient.execute(httppost);    
  82.             HttpEntity entity = response.getEntity();    
  83.             if (entity != null) {    
  84.                   System.out.println(EntityUtils.toString(entity, "UTF-8"));    
  85.             }    
  86.             //释放连接  
  87.         } catch (Exception e) {  
  88.             throw e;  
  89.         }finally{  
  90.              httpclient.close();  
  91.              response.close();  
  92.         }  
  93.     }    
  94.       
  95.     /**  
  96.      * 发送 get请求  
  97.      * @throws Exception  
  98.      */    
  99.     public static void get() throws Exception {    
  100.         CloseableHttpClient httpclient = null;  
  101.         CloseableHttpResponse response = null;  
  102.         try {  
  103.             httpclient = HttpClients.createDefault();    
  104.             // 创建httpget.      
  105.             HttpGet httpget = new HttpGet("http://www.baidu.com/");    
  106.             // 执行get请求.      
  107.             response = httpclient.execute(httpget);    
  108.             // 获取响应实体      
  109.             HttpEntity entity = response.getEntity();    
  110.         
  111.             // 打印响应状态      
  112.             System.out.println(response.getStatusLine().getStatusCode());    
  113.             if (entity != null) {    
  114.                 // 打印响应内容      
  115.                 System.out.println("Response content: " + EntityUtils.toString(entity));    
  116.             }  
  117.         } catch (Exception e) {  
  118.             throw e;  
  119.         }finally{  
  120.             httpclient.close();  
  121.             response.close();  
  122.         }  
  123.     }  
  124. }  

 

 

五、SSL跟上传文件实例

 

Java代码   收藏代码
  1. package com.test;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.io.UnsupportedEncodingException;  
  7. import java.security.KeyManagementException;  
  8. import java.security.KeyStore;  
  9. import java.security.KeyStoreException;  
  10. import java.security.NoSuchAlgorithmException;  
  11. import java.security.cert.CertificateException;  
  12. import java.util.ArrayList;  
  13. import java.util.List;  
  14. import javax.net.ssl.SSLContext;  
  15. import org.apache.http.HttpEntity;  
  16. import org.apache.http.NameValuePair;  
  17. import org.apache.http.ParseException;  
  18. import org.apache.http.client.ClientProtocolException;  
  19. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  20. import org.apache.http.client.methods.CloseableHttpResponse;  
  21. import org.apache.http.client.methods.HttpGet;  
  22. import org.apache.http.client.methods.HttpPost;  
  23. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  24. import org.apache.http.conn.ssl.SSLContexts;  
  25. import org.apache.http.conn.ssl.TrustSelfSignedStrategy;  
  26. import org.apache.http.entity.ContentType;  
  27. import org.apache.http.entity.mime.MultipartEntityBuilder;  
  28. import org.apache.http.entity.mime.content.FileBody;  
  29. import org.apache.http.entity.mime.content.StringBody;  
  30. import org.apache.http.impl.client.CloseableHttpClient;  
  31. import org.apache.http.impl.client.HttpClients;  
  32. import org.apache.http.message.BasicNameValuePair;  
  33. import org.apache.http.util.EntityUtils;  
  34. import org.junit.Test;  
  35.   
  36. public class HttpClientTest {  
  37.   
  38.     @Test  
  39.     public void jUnitTest() {  
  40.         ssl();  
  41.     }  
  42.   
  43.     /** 
  44.      * HttpClient连接SSL 
  45.      */  
  46.     public void ssl() {  
  47.         CloseableHttpClient httpclient = null;  
  48.         try {  
  49.             KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
  50.             FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));  
  51.             try {  
  52.                 // 加载keyStore d:\\tomcat.keystore    
  53.                 trustStore.load(instream, "123456".toCharArray());  
  54.             } catch (CertificateException e) {  
  55.                 e.printStackTrace();  
  56.             } finally {  
  57.                 try {  
  58.                     instream.close();  
  59.                 } catch (Exception ignore) {  
  60.                 }  
  61.             }  
  62.             // 相信自己的CA和所有自签名的证书  
  63.             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();  
  64.             // 只允许使用TLSv1协议  
  65.             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,  
  66.                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);  
  67.             httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();  
  68.             // 创建http请求(get方式)  
  69.             HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");  
  70.             System.out.println("executing request" + httpget.getRequestLine());  
  71.             CloseableHttpResponse response = httpclient.execute(httpget);  
  72.             try {  
  73.                 HttpEntity entity = response.getEntity();  
  74.                 System.out.println("----------------------------------------");  
  75.                 System.out.println(response.getStatusLine());  
  76.                 if (entity != null) {  
  77.                     System.out.println("Response content length: " + entity.getContentLength());  
  78.                     System.out.println(EntityUtils.toString(entity));  
  79.                     EntityUtils.consume(entity);  
  80.                 }  
  81.             } finally {  
  82.                 response.close();  
  83.             }  
  84.         } catch (ParseException e) {  
  85.             e.printStackTrace();  
  86.         } catch (IOException e) {  
  87.             e.printStackTrace();  
  88.         } catch (KeyManagementException e) {  
  89.             e.printStackTrace();  
  90.         } catch (NoSuchAlgorithmException e) {  
  91.             e.printStackTrace();  
  92.         } catch (KeyStoreException e) {  
  93.             e.printStackTrace();  
  94.         } finally {  
  95.             if (httpclient != null) {  
  96.                 try {  
  97.                     httpclient.close();  
  98.                 } catch (IOException e) {  
  99.                     e.printStackTrace();  
  100.                 }  
  101.             }  
  102.         }  
  103.     }  
  104.   
  105.     /** 
  106.      * 上传文件 
  107.      */  
  108.     public void upload() {  
  109.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  110.         try {  
  111.             HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");  
  112.   
  113.             FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));  
  114.             StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);  
  115.   
  116.             HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();  
  117.   
  118.             httppost.setEntity(reqEntity);  
  119.   
  120.             System.out.println("executing request " + httppost.getRequestLine());  
  121.             CloseableHttpResponse response = httpclient.execute(httppost);  
  122.             try {  
  123.                 System.out.println("----------------------------------------");  
  124.                 System.out.println(response.getStatusLine());  
  125.                 HttpEntity resEntity = response.getEntity();  
  126.                 if (resEntity != null) {  
  127.                     System.out.println("Response content length: " + resEntity.getContentLength());  
  128.                 }  
  129.                 EntityUtils.consume(resEntity);  
  130.             } finally {  
  131.                 response.close();  
  132.             }  
  133.         } catch (ClientProtocolException e) {  
  134.             e.printStackTrace();  
  135.         } catch (IOException e) {  
  136.             e.printStackTrace();  
  137.         } finally {  
  138.             try {  
  139.                 httpclient.close();  
  140.             } catch (IOException e) {  
  141.                 e.printStackTrace();  
  142.             }  
  143.         }  
  144.     }  
  145. }  

   本实例是采用HttpClient4.3最新版本。该版本与之前的代码写法风格相差较大,大家多留意下。

 

参考:http://blog.csdn.net/wangpeng047/article/details/19624529

这篇关于Apache HttpClient使用详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1148117

相关文章

Debezium 与 Apache Kafka 的集成方式步骤详解

《Debezium与ApacheKafka的集成方式步骤详解》本文详细介绍了如何将Debezium与ApacheKafka集成,包括集成概述、步骤、注意事项等,通过KafkaConnect,D... 目录一、集成概述二、集成步骤1. 准备 Kafka 环境2. 配置 Kafka Connect3. 安装 D

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

Spring Cloud LoadBalancer 负载均衡详解

《SpringCloudLoadBalancer负载均衡详解》本文介绍了如何在SpringCloud中使用SpringCloudLoadBalancer实现客户端负载均衡,并详细讲解了轮询策略和... 目录1. 在 idea 上运行多个服务2. 问题引入3. 负载均衡4. Spring Cloud Load

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景