1、HttpClient相关的重要资料

官方网站:http://hc.apache.org/

API:http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/apidocs/index.html

tutorial: http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/html/index.html  【PDF版本】http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/pdf/httpclient-tutorial.pdf

2、HttpClient有2个版本

org.apache.http.impl.client.HttpClients 与 org.apache.commons.httpclient.HttpClient

目前后者已被废弃,apache已不再支持。

一般而言,使用HttpClient均需导入httpclient.jar与httpclient-core.jar2个包。

3、使用HttpClient进行网络处理的基本步骤

(1)通过get的方式获取到Response对象。

[java] view
plain
copy

  1. CloseableHttpClient httpClient = HttpClients.createDefault();
  2. HttpGet httpGet = new HttpGet("http://www.baidu.com/");
  3. CloseableHttpResponse response = httpClient.execute(httpGet);

注意,必需要加上http://的前缀,否则会报:Target host is null异常。

(2)获取Response对象的Entity。

[java] view
plain
copy

  1. HttpEntity entity = response.getEntity();

注:HttpClient将Response的正文及Request的POST/PUT方法中的正文均封装成一个HttpEntity对象。可以通过entity.getContenType(),entity.getContentLength()等方法获取到正文的相关信息。但最重要的方法是通过getContent()获取到InputStream对象。

(3)通过Entity获取到InputStream对象,然后对返回内容进行处理。

[java] view
plain
copy

  1. is = entity.getContent();
  2. sc = new Scanner(is);
  3. // String filename = path.substring(path.lastIndexOf('/')+1);
  4. String filename = "2.txt";
  5. os = new PrintWriter(filename);
  6. while (sc.hasNext()) {
  7. os.write(sc.nextLine());
  8. }

使用HtppClient下载一个网页的完整代码如下:

[java] view
plain
copy

  1. package com.ljh.test;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.PrintWriter;
  5. import java.io.Writer;
  6. import java.util.Scanner;
  7. import org.apache.http.HttpEntity;
  8. import org.apache.http.HttpStatus;
  9. import org.apache.http.client.ClientProtocolException;
  10. import org.apache.http.client.methods.CloseableHttpResponse;
  11. import org.apache.http.client.methods.HttpGet;
  12. import org.apache.http.impl.client.CloseableHttpClient;
  13. import org.apache.http.impl.client.HttpClients;
  14. public class DownloadWebPage{
  15. public static void downloadPagebyGetMethod() throws IOException {
  16. // 1、通过HttpGet获取到response对象
  17. CloseableHttpClient httpClient = HttpClients.createDefault();
  18. HttpGet httpGet = new HttpGet("http://www.baidu.com/");
  19. CloseableHttpResponse response = httpClient.execute(httpGet);
  20. InputStream is = null;
  21. Scanner sc = null;
  22. Writer os = null;
  23. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  24. try {
  25. // 2、获取response的entity。
  26. HttpEntity entity = response.getEntity();
  27. // 3、获取到InputStream对象,并对内容进行处理
  28. is = entity.getContent();
  29. sc = new Scanner(is);
  30. // String filename = path.substring(path.lastIndexOf('/')+1);
  31. String filename = "2.txt";
  32. os = new PrintWriter(filename);
  33. while (sc.hasNext()) {
  34. os.write(sc.nextLine());
  35. }
  36. } catch (ClientProtocolException e) {
  37. e.printStackTrace();
  38. } finally {
  39. if (sc != null) {
  40. sc.close();
  41. }
  42. if (is != null) {
  43. is.close();
  44. }
  45. if (os != null) {
  46. os.close();
  47. }
  48. if (response != null) {
  49. response.close();
  50. }
  51. }
  52. }
  53. }
  54. public static void main(String[] args) {
  55. try {
  56. downloadPagebyGetMethod();
  57. } catch (IOException e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. }

注意:直接将HttpGet改为HttpPost,返回的结果有误,百度返回302状态,即重定向,新浪返回拒绝访问。怀疑大多网站均不允许POST方法直接访问网站。

HttpClient基础教程的更多相关文章

  1. HttpClient基础教程 分类: C_OHTERS 2014-05-18 23:23 2600人阅读 评论(0) 收藏

    1.HttpClient相关的重要资料 官方网站:http://hc.apache.org/ API:http://hc.apache.org/httpcomponents-client-4.3.x/ ...

  2. matlab基础教程——根据Andrew Ng的machine learning整理

    matlab基础教程--根据Andrew Ng的machine learning整理 基本运算 算数运算 逻辑运算 格式化输出 小数位全局修改 向量和矩阵运算 矩阵操作 申明一个矩阵或向量 快速建立一 ...

  3. <<Bootstrap基础教程>> 新书出手,有心栽花花不开,无心插柳柳成荫

    并非闲的蛋疼,做技术也经常喜欢蛋疼,纠结于各种技术,各种需求变更,还有一个很苦恼的就是UI总是那么不尽人意.前不久自己开源了自己做了多年的仓储项目(开源地址:https://github.com/he ...

  4. Memcache教程 Memcache零基础教程

    Memcache是什么 Memcache是danga.com的一个项目,来分担数据库的压力. 它可以应对任意多个连接,使用非阻塞的网络IO.由于它的工作机制是在内存中开辟一块空间,然后建立一个Hash ...

  5. Selenium IDE 基础教程

    Selenium IDE 基础教程 1.下载安装     a 在火狐浏览其中搜索附件组件,查找 Selenium IDE     b 下载安装,然后重启firefox 2.界面讲解      在菜单- ...

  6. html快速入门(基础教程+资源推荐)

    1.html究竟是什么? 从字面上理解,html是超文本标记语言hyper text mark-up language的首字母缩写,指的是一种通用web页面描述语言,是用来描述我们打开浏览器就能看到的 ...

  7. 转发-UI基础教程 – 原生App切图的那些事儿

    UI基础教程 – 原生App切图的那些事儿 转发:http://www.shejidaren.com/app-ui-cut-and-slice.html 移动APP切图是UI设计必须学会的一项技能,切 ...

  8. 【Unity3D基础教程】给初学者看的Unity教程(四):通过制作Flappy Bird了解Native 2D中的RigidBody2D和Collider2D

    作者:王选易,出处:http://www.cnblogs.com/neverdie/ 欢迎转载,也请保留这段声明.如果你喜欢这篇文章,请点[推荐].谢谢! 引子 在第一篇文章[Unity3D基础教程] ...

  9. oracle基础教程(8)oracle修改字符集

    oracle基础教程(8)oracle修改字符集 1.用dba连接数据库 -->sqlplus / as sysdba 2.查看字符集 -->SELECT parameter, value ...

随机推荐

  1. [C++程序设计]引用

    对一个数据可以使用“引用”(reference),这是C++对C的一个重要扩充,引用是一种新的变量类型,它的作用是为一个变量起一个别名.假如有一个变量a,想给它起一个别名b,可以这样写:int a; ...

  2. Ecstore中的微信支付怎么样配置

    要在Ecstore中开启微信支付,需要先在后台/应用中心中安装“移动商城”和“微信商城管理”这两个App移动商城App是ecstore的手机wap版,可在手机浏览器中实现商城的B2c购物功能.“微信商 ...

  3. zend framework 初识

    1. 请求顺序 : index.php --> Bootstrap.php --> IndexController.php 2. 验证顺序 : Bootstrap.php function ...

  4. html简单定位

    (1) 两个块水平排列 将两个块都设为浮动即可.注意不能将两个块的position属性设为absolute(绝对定位) #div1{ background-color: red; float:left ...

  5. javaweb jsp页面上传excel文件

    servlet: private static final long FILE_MAX_SIZE = 4 * 1024 * 1024; if (!ServletFileUpload.isMultipa ...

  6. QSizePolicy可均匀调整控件的大小,还可设置比例,非常完美(每个QWidget都有这个功能)

    http://blog.csdn.net/liang19890820/article/details/51986284 它是QWidget的固有属性: http://doc.qt.io/qt-4.8/ ...

  7. ant的入门 配置与安装

    最近需要用ant来生成文件,java类.我才开始了解了这个工具.仔细看了一下,感觉这个小工具的强大功能. 博主也是初学者,在网上收集了资料,尝试了配置:感觉有些高手写得不错变引用之. 配置如下: 以上 ...

  8. nginx+vaadin配置

    nginx+Vaadin的特殊性在于配置WEBSOCKET或LONG_POLLING.网上资料不多,自己多次尝试配置都不成功,后来终于找到这篇说明才得以配置成功,使用效果不错,介绍如下. 1./etc ...

  9. LeeCode-Rotate Array

    Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array  ...

  10. ZOJ3578(Matrix)

    Matrix Time Limit: 10 Seconds      Memory Limit: 131072 KB A N*M coordinate plane ((0, 0)~(n, m)). I ...