HttpClient使用及注意事项

先介绍几个好网站:

  httpclient入门:  http://www.ibm.com/developerworks/cn/opensource/os-httpclient/ 
  httpclient证书导入:http://www.blogjava.net/happytian/archive/2006/12/22/89447.html 
  httpclient高级认识:http://laohuang.iteye.com/blog/55613 
  httpclient官方文档:http://hc.apache.org/httpcomponents-client/index.html 
  httpclient资源关闭:http://www.iteye.com/topic/234759
  例子:http://blog.csdn.net/z69183787/article/details/19153369

然后呢,就是那句话。。。好东西转载、学习一个都不能少,下边的转自这里

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

一、简介

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

下载地址: http://hc.apache.org/downloads.cgi

二、特性

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

三、使用方法

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

四、实例

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1.   
  2. public class HttpClientTest {  
  3.   
  4.     @Test  
  5.     public void jUnitTest() {  
  6.         get();  
  7.     }  
  8.   
  9.     /** 
  10.      * HttpClient连接SSL 
  11.      */  
  12.     public void ssl() {  
  13.         CloseableHttpClient httpclient = null;  
  14.         try {  
  15.             KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
  16.             FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));  
  17.             try {  
  18.                 // 加载keyStore d:\\tomcat.keystore    
  19.                 trustStore.load(instream, "123456".toCharArray());  
  20.             } catch (CertificateException e) {  
  21.                 e.printStackTrace();  
  22.             } finally {  
  23.                 try {  
  24.                     instream.close();  
  25.                 } catch (Exception ignore) {  
  26.                 }  
  27.             }  
  28.             // 相信自己的CA和所有自签名的证书  
  29.             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();  
  30.             // 只允许使用TLSv1协议  
  31.             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,  
  32.                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);  
  33.             httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();  
  34.             // 创建http请求(get方式)  
  35.             HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");  
  36.             System.out.println("executing request" + httpget.getRequestLine());  
  37.             CloseableHttpResponse response = httpclient.execute(httpget);  
  38.             try {  
  39.                 HttpEntity entity = response.getEntity();  
  40.                 System.out.println("----------------------------------------");  
  41.                 System.out.println(response.getStatusLine());  
  42.                 if (entity != null) {  
  43.                     System.out.println("Response content length: " + entity.getContentLength());  
  44.                     System.out.println(EntityUtils.toString(entity));  
  45.                     EntityUtils.consume(entity);  
  46.                 }  
  47.             } finally {  
  48.                 response.close();  
  49.             }  
  50.         } catch (ParseException e) {  
  51.             e.printStackTrace();  
  52.         } catch (IOException e) {  
  53.             e.printStackTrace();  
  54.         } catch (KeyManagementException e) {  
  55.             e.printStackTrace();  
  56.         } catch (NoSuchAlgorithmException e) {  
  57.             e.printStackTrace();  
  58.         } catch (KeyStoreException e) {  
  59.             e.printStackTrace();  
  60.         } finally {  
  61.             if (httpclient != null) {  
  62.                 try {  
  63.                     httpclient.close();  
  64.                 } catch (IOException e) {  
  65.                     e.printStackTrace();  
  66.                 }  
  67.             }  
  68.         }  
  69.     }  
  70.   
  71.     /** 
  72.      * post方式提交表单(模拟用户登录请求) 
  73.      */  
  74.     public void postForm() {  
  75.         // 创建默认的httpClient实例.    
  76.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  77.         // 创建httppost    
  78.         HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");  
  79.         // 创建参数队列    
  80.         List<namevaluepair> formparams = new ArrayList<namevaluepair>();  
  81.         formparams.add(new BasicNameValuePair("username""admin"));  
  82.         formparams.add(new BasicNameValuePair("password""123456"));  
  83.         UrlEncodedFormEntity uefEntity;  
  84.         try {  
  85.             uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
  86.             httppost.setEntity(uefEntity);  
  87.             System.out.println("executing request " + httppost.getURI());  
  88.             CloseableHttpResponse response = httpclient.execute(httppost);  
  89.             try {  
  90.                 HttpEntity entity = response.getEntity();  
  91.                 if (entity != null) {  
  92.                     System.out.println("--------------------------------------");  
  93.                     System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));  
  94.                     System.out.println("--------------------------------------");  
  95.                 }  
  96.             } finally {  
  97.                 response.close();  
  98.             }  
  99.         } catch (ClientProtocolException e) {  
  100.             e.printStackTrace();  
  101.         } catch (UnsupportedEncodingException e1) {  
  102.             e1.printStackTrace();  
  103.         } catch (IOException e) {  
  104.             e.printStackTrace();  
  105.         } finally {  
  106.             // 关闭连接,释放资源    
  107.             try {  
  108.                 httpclient.close();  
  109.             } catch (IOException e) {  
  110.                 e.printStackTrace();  
  111.             }  
  112.         }  
  113.     }  
  114.   
  115.     /** 
  116.      * 发送 post请求访问本地应用并根据传递参数不同返回不同结果 
  117.      */  
  118.     public void post() {  
  119.         // 创建默认的httpClient实例.    
  120.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  121.         // 创建httppost    
  122.         HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");  
  123.         // 创建参数队列    
  124.         List<namevaluepair> formparams = new ArrayList<namevaluepair>();  
  125.         formparams.add(new BasicNameValuePair("type""house"));  
  126.         UrlEncodedFormEntity uefEntity;  
  127.         try {  
  128.             uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
  129.             httppost.setEntity(uefEntity);  
  130.             System.out.println("executing request " + httppost.getURI());  
  131.             CloseableHttpResponse response = httpclient.execute(httppost);  
  132.             try {  
  133.                 HttpEntity entity = response.getEntity();  
  134.                 if (entity != null) {  
  135.                     System.out.println("--------------------------------------");  
  136.                     System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));  
  137.                     System.out.println("--------------------------------------");  
  138.                 }  
  139.             } finally {  
  140.                 response.close();  
  141.             }  
  142.         } catch (ClientProtocolException e) {  
  143.             e.printStackTrace();  
  144.         } catch (UnsupportedEncodingException e1) {  
  145.             e1.printStackTrace();  
  146.         } catch (IOException e) {  
  147.             e.printStackTrace();  
  148.         } finally {  
  149.             // 关闭连接,释放资源    
  150.             try {  
  151.                 httpclient.close();  
  152.             } catch (IOException e) {  
  153.                 e.printStackTrace();  
  154.             }  
  155.         }  
  156.     }  
  157.   
  158.     /** 
  159.      * 发送 get请求 
  160.      */  
  161.     public void get() {  
  162.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  163.         try {  
  164.             // 创建httpget.    
  165.             HttpGet httpget = new HttpGet("http://www.baidu.com/");  
  166.             System.out.println("executing request " + httpget.getURI());  
  167.             // 执行get请求.    
  168.             CloseableHttpResponse response = httpclient.execute(httpget);  
  169.             try {  
  170.                 // 获取响应实体    
  171.                 HttpEntity entity = response.getEntity();  
  172.                 System.out.println("--------------------------------------");  
  173.                 // 打印响应状态    
  174.                 System.out.println(response.getStatusLine());  
  175.                 if (entity != null) {  
  176.                     // 打印响应内容长度    
  177.                     System.out.println("Response content length: " + entity.getContentLength());  
  178.                     // 打印响应内容    
  179.                     System.out.println("Response content: " + EntityUtils.toString(entity));  
  180.                 }  
  181.                 System.out.println("------------------------------------");  
  182.             } finally {  
  183.                 response.close();  
  184.             }  
  185.         } catch (ClientProtocolException e) {  
  186.             e.printStackTrace();  
  187.         } catch (ParseException e) {  
  188.             e.printStackTrace();  
  189.         } catch (IOException e) {  
  190.             e.printStackTrace();  
  191.         } finally {  
  192.             // 关闭连接,释放资源    
  193.             try {  
  194.                 httpclient.close();  
  195.             } catch (IOException e) {  
  196.                 e.printStackTrace();  
  197.             }  
  198.         }  
  199.     }  
  200.   
  201.     /** 
  202.      * 上传文件 
  203.      */  
  204.     public void upload() {  
  205.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  206.         try {  
  207.             HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");  
  208.   
  209.             FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));  
  210.             StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);  
  211.   
  212.             HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();  
  213.   
  214.             httppost.setEntity(reqEntity);  
  215.   
  216.             System.out.println("executing request " + httppost.getRequestLine());  
  217.             CloseableHttpResponse response = httpclient.execute(httppost);  
  218.             try {  
  219.                 System.out.println("----------------------------------------");  
  220.                 System.out.println(response.getStatusLine());  
  221.                 HttpEntity resEntity = response.getEntity();  
  222.                 if (resEntity != null) {  
  223.                     System.out.println("Response content length: " + resEntity.getContentLength());  
  224.                 }  
  225.                 EntityUtils.consume(resEntity);  
  226.             } finally {  
  227.                 response.close();  
  228.             }  
  229.         } catch (ClientProtocolException e) {  
  230.             e.printStackTrace();  
  231.         } catch (IOException e) {  
  232.             e.printStackTrace();  
  233.         } finally {  
  234.             try {  
  235.                 httpclient.close();  
  236.             } catch (IOException e) {  
  237.                 e.printStackTrace();  
  238.             }  
  239.         }  
  240.     }  
  241. }</namevaluepair></namevaluepair></namevaluepair></namevaluepair>  

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


还是那句话。。。好东西转载、学习一个都不能少,下边的转自这里

HttpClient在应用中有些需要注意的几个地方:

   生成HttpClient的地方:

   ttpClient=new HttpClient();
  httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

 第一:一定要有下边这两个参数设置,否则会生成多个Cookie header送给web server
  httpClient.getParams().setParameter("http.protocol.single-cookie-header",true);
  httpClient.getParams().setParameter("http.protocol.content-charset","gb2312");
  ArrayList headerList=new ArrayList();
  Header accept=new Header("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-silverlight, */*");
  headerList.add(accept);
    ...... 

  httpClient.getParams().setParameter("http.default-headers",headerList);
  httpClient.getParams().setParameter("http.protocol.version",HttpVersion.HTTP_1_1);
  httpClient.getParams().setParameter("http.method.retry-handler",new DefaultHttpMethodRetryHandler());

   

  第二:在生成httpMethod的地方:

     PostMethod postMethod =new PostMethod();
  postMethod.getParams().setUriCharset("GB2312");

     postMethod.setURI(new URI(url,false,"GB2312"));

     client.executeMethod(postMethod); 

   以上可避免送出类似“HTTP://127.0.0.1:8080/action.do?content=一二三四五六”的URL时出现URI报错;

 第三:ConnectionPoolTimeoutException问题,导致的原因可能有这几个:

1.设置连接超时时间 未设置或设置过小;

2.请求后的连接是否已经释放;

想了解更多,以及参数设置及代码写法、存在的风险 请看这篇文章


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
目标检测(Object Detection)是计算机视觉领域的一个核心问题,其主要任务是找出图像中所有感兴趣的目标(物体),并确定它们的类别和位置。以下是对目标检测的详细阐述: 一、基本概念 目标检测的任务是解决“在哪里?是什么?”的问题,即定位出图像中目标的位置并识别出目标的类别。由于各类物体具有不同的外观、形状和姿态,加上成像时光照、遮挡等因素的干扰,目标检测一直是计算机视觉领域最具挑战性的任务之一。 二、核心问题 目标检测涉及以下几个核心问题: 分类问题:判断图像中的目标属于哪个类别。 定位问题:确定目标在图像中的具体位置。 大小问题:目标可能具有不同的大小。 形状问题:目标可能具有不同的形状。 三、算法分类 基于深度学习的目标检测算法主要分为两大类: Two-stage算法:先进行区域生成(Region Proposal),生成有可能包含待检物体的预选框(Region Proposal),再通过卷积神经网络进行样本分类。常见的Two-stage算法包括R-CNN、Fast R-CNN、Faster R-CNN等。 One-stage算法:不用生成区域提议,直接在网络中提取特征来预测物体分类和位置。常见的One-stage算法包括YOLO系列(YOLOv1、YOLOv2、YOLOv3、YOLOv4、YOLOv5等)、SSD和RetinaNet等。 四、算法原理 以YOLO系列为例,YOLO将目标检测视为回归问题,将输入图像一次性划分为多个区域,直接在输出层预测边界框和类别概率。YOLO采用卷积网络来提取特征,使用全连接层来得到预测值。其网络结构通常包含多个卷积层和全连接层,通过卷积层提取图像特征,通过全连接层输出预测结果。 五、应用领域 目标检测技术已经广泛应用于各个领域,为人们的生活带来了极大的便利。以下是一些主要的应用领域: 安全监控:在商场、银行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值