利用HttpClient获取网页内容

HTTP协议是目前互联网上最重要的协议,许多软件与服务都需要依赖HTTP协议。
虽然java.net这个package中包含了对HTTP的基本支持,但还有很多高级和复杂的功能无法实现,这不能不说是一个遗憾。
HttpClient作为Apache的开源项目项目之一,为基于HTTP协议的操作提供了强大的客户端执行支持,最新的版本为3.0RC3。
下面通过一个例子简要展示HttpClient的使用方法:

--------------------------------------------------------------------------------
import java.io.BufferedReader;
import java.io.IOException;

JAVA手机网[www.cnjm.net]
import java.io.InputStream;
import java.io.InputStreamReader;
iimport java.io.UnsupportedEncodingException;

import java.util.*;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnection;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

/**
* @author steven
*/
public class HttpClientExample {

//获得ConnectionManager,设置相关参数
private static MultiThreadedHttpConnectionManager manager =
new MultiThreadedHttpConnectionManager();
private static int connectionTimeOut = 20000;
private static int socketTimeOut = 10000;
private static int maxConnectionPerHost = 5;
private static int maxTotalConnections = 40;

//标志初始化是否完成的flag
private static boolean initialed = false;

//初始化ConnectionManger的方法
public static void SetPara() {
manager.getParams().setConnectionTimeout(connectionTimeOut);
manager.getParams().setSoTimeout(socketTimeOut);
manager.getParams()
.setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
manager.getParams().setMaxTotalConnections(maxTotalConnections);
initialed = true;
JAVA手机网[www.cnjm.net]
}

//通过get方法获取网页内容
public static String getGetResponseWithHttpClient(String url, String encode) {
JAVA手机网[www.cnjm.net]
HttpClient client = new HttpClient(manager);

if (initialed) {
JAVA手机网[www.cnjm.net]
HttpClientExample.SetPara();
}

GetMethod get = new GetMethod(url);
get.setFollowRedirects(true);

JAVA手机网[www.cnjm.net]
String result = null;
StringBuffer resultBuffer = new StringBuffer();

try {

client.executeMethod(get);
JAVA手机网[www.cnjm.net]

JAVA手机网[www.cnjm.net]
//在目标页面情况未知的条件下,不推荐使用getResponseBodyAsString()方法
//String strGetResponseBody = post.getResponseBodyAsString();
BufferedReader in = new BufferedReader(
new InputStreamReader(
get.getResponseBodyAsStream(),
get.getResponseCharSet()));

String inputLine = null;

while ((inputLine = in.readLine()) != null) {
resultBuffer.append(inputLine);
JAVA手机网[www.cnjm.net]
resultBuffer.append("/n");
}

in.close();

result = resultBuffer.toString();

//iso-8859-1 is the default reading encode
result = HttpClientExample.ConverterStringCode(resultBuffer.toString(),
get.getResponseCharSet(),
encode);
} catch (Exception e) {
e.printStackTrace();

result = "";
JAVA手机网[www.cnjm.net]
} finally {
get.releaseConnection();

return result;
}
}

public static String getPostResponseWithHttpClient(String url,
String encode) {
HttpClient client = new HttpClient(manager);
JAVA手机网[www.cnjm.net]

if (initialed) {
HttpClientExample.SetPara();
}

JAVA手机网[www.cnjm.net]
PostMethod post = new PostMethod(url);
post.setFollowRedirects(false);

StringBuffer resultBuffer = new StringBuffer();

String result = null;

try {
client.executeMethod(post);

BufferedReader in = new BufferedReader(
JAVA手机网[www.cnjm.net]
new InputStreamReader(
post.getResponseBodyAsStream(),
post.getResponseCharSet()));
String inputLine = null;

JAVA手机网[www.cnjm.net]
while ((inputLine = in.readLine()) != null) {
resultBuffer.append(inputLine);
JAVA手机网[www.cnjm.net]
resultBuffer.append("/n");
}

in.close();

//iso-8859-1 is the default reading encode
result = HttpClientExample.ConverterStringCode(resultBuffer.toString(),
post.getResponseCharSet(),
encode);
} catch (Exception e) {
e.printStackTrace();

result = "";
JAVA手机网[www.cnjm.net]
} finally {
post.releaseConnection();

JAVA手机网[www.cnjm.net]
return result;
}
}

public static String getPostResponseWithHttpClient(String url,
String encode,
NameValuePair[] nameValuePair) {
HttpClient client = new HttpClient(manager);

if (initialed) {
HttpClientExample.SetPara();
}

JAVA手机网[www.cnjm.net]
PostMethod post = new PostMethod(url);
post.setRequestBody(nameValuePair);
post.setFollowRedirects(false);
JAVA手机网[www.cnjm.net]

String result = null;
StringBuffer resultBuffer = new StringBuffer();

try {
client.executeMethod(post);
BufferedReader in = new BufferedReader(
new InputStreamReader(
post.getResponseBodyAsStream(),
post.getResponseCharSet()));
String inputLine = null;

while ((inputLine = in.readLine()) != null) {
JAVA手机网[www.cnjm.net]
resultBuffer.append(inputLine);
resultBuffer.append("/n");
}

in.close();
JAVA手机网[www.cnjm.net]


//iso-8859-1 is the default reading encode
result = HttpClientExample.ConverterStringCode(resultBuffer.toString(),
post.getResponseCharSet(),
encode);
} catch (Exception e) {
e.printStackTrace();

JAVA手机网[www.cnjm.net]
result = "";
} finally {
post.releaseConnection();

return result;
}
}

JAVA手机网[www.cnjm.net]
private static String ConverterStringCode(String source, String srcEncode, String destEncode) {
if (src != null) {
try {
return new String(src.getBytes(srcEncode), destEncode);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
} else {
return "";
JAVA手机网[www.cnjm.net]
}
}
}

--------------------------------------------------------------------------------
之后,就可以通过下面的代码获得目标网页:
String source = HttpClientExample.getGetResponseWithHttpClient("www.sina.com.cn", "GBK");

注意,在默认情况下,HttpClient的Request的Head中
User-Agent的值是Jakarta Commons-HttpClient 3.0RC1,如果需要改变它(例如,变为Mozilla/4.0),必须在调用之前运行如下语句:
System.getProperties().setProperty("httpclient.useragent", "Mozilla/4.0");


压缩包中含有多个文档,从了解httpclient到应用。 httpClient 1httpClint 1.1简介 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。 下载地址:  http://hc.apache.org/downloads.cgi 1.2特性 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 可免费获取。 1.3版本 org.apache.http.impl.client.HttpClients 与 org.apache.commons.httpclient.HttpClient目前后者已被废弃,apache已不再支持。 一般而言,使用HttpClient均需导入httpclient.jar与httpclient-core.jar2个包。 1.4使用方法与步骤 开发环境:需要 使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。 1.创建HttpClient对象。 HttpClient client = new HttpClient(); 2.创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。 //使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的 http换成https HttpMethod method = new GetMethod("http://www.baidu.com"); //使用POST方法 HttpMethod method = new PostMethod("http://java.sun.com";); 3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。 3.调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。 client.executeMethod(method); 5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。 6. 释放连接。无论执行方法是否成功,都必须释放连接 //打印服务器返回的状态 System.out.println(method.getStatusLine()); //打印返回的信息 System.out.println(method.getResponseBodyAsString(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值