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

相关文章

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

SpringBoot3.4配置校验新特性的用法详解

《SpringBoot3.4配置校验新特性的用法详解》SpringBoot3.4对配置校验支持进行了全面升级,这篇文章为大家详细介绍了一下它们的具体使用,文中的示例代码讲解详细,感兴趣的小伙伴可以参考... 目录基本用法示例定义配置类配置 application.yml注入使用嵌套对象与集合元素深度校验开发

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

Java Spring 中 @PostConstruct 注解使用原理及常见场景

《JavaSpring中@PostConstruct注解使用原理及常见场景》在JavaSpring中,@PostConstruct注解是一个非常实用的功能,它允许开发者在Spring容器完全初... 目录一、@PostConstruct 注解概述二、@PostConstruct 注解的基本使用2.1 基本代

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

springboot使用Scheduling实现动态增删启停定时任务教程

《springboot使用Scheduling实现动态增删启停定时任务教程》:本文主要介绍springboot使用Scheduling实现动态增删启停定时任务教程,具有很好的参考价值,希望对大家有... 目录1、配置定时任务需要的线程池2、创建ScheduledFuture的包装类3、注册定时任务,增加、删