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. LP64是什么意思

    在64位机器上,如果int是32位,long是64位,pointer也是64位,那么该机器就是LP64的,其中的L表示Long,P表示Pointer,64表示Long和Pointer都是64位的.由于 ...

  2. PHP--变量部分知识点

    PHP全局变量 PHP全局变量作用域不同与C,在函数内部不可以使用全局变量,要在函数内部使用全局变量需要,global $var或者使用超全局变量数组$GLOBALS['var']. 静态变量 PHP ...

  3. 为什么在CSS中不要再使用@import

    http://www.stevesouders.com/blog/2009/04/09/dont-use-import/为什么在CSS中不要再使用@import

  4. CI(CodeIgniter)学习第二讲

    一.CI的文件结构: 了解CI的文件结构可以帮助我们快速的对CI框架有一个整体的认识,就好像我们去了一个陌生的城市一样,对你来讲周围的一切都是陌生和未知的,要想快速的了解这座城市,你可以买一张这座城市 ...

  5. python基础教程第4章——字典

    1.映射(mapping):通过名字引用值的数据结构.字典是Python中唯一内建的映射类型,字典中的值并没有特殊的顺序,但是都存储在一个特定的键(key)里.键可以是数字.字符串甚至是元组. 2.字 ...

  6. Python读写Json文件

    一个小例子,使用Json配置文件 # -*- coding: utf-8 -*- import json import time def store(data): with open('data.js ...

  7. Nginx 的 Location 配置指令块

    最近一段时间在学习 Nginx ,以前一直对 Nginx 的 Location 配置很头大,最近终于弄出点眉目.总结如下:nginx 配置文件,自下到上分为三种层次分明的结构: |    http b ...

  8. 51单片机实现对24C02进行页写、顺序读取并显示验证

    //************************************************************************************* //**程序名称:51单 ...

  9. 从Qt4到Qt5的,主要的进化有三(对于QtWidget的精简和优化会很有限)

    从Qt4到Qt5的,主要的进化有三:1 语言的进化,原来是基于C++(qtwidget)和XML(.ui),现在添加了QML(QtQuick)+JS(v8)的架构.2 绘图系统的进化,原先基于QPai ...

  10. CentOS安装错误:no default or ui configuration

    靠,以后再也不用浏览器自带的下载工具下载镜像文件了,原来是下载的不完整,但是显示完全下载完毕了,真特么误导人.文件的checksum不对. references: https://www.centos ...