HttpClient 代理实例(Get方式)
使用的jar包:
commons-codec-1.4.jar
commons-httpclient.jar
commons-logging-1.1.1.jar
httpclient-4.1.2.jar
httpclient-cache-4.1.2.jar
httpcore-4.1.2.jar
httpmime-4.1.2.jar
使用 HttpClient 需要以下 6 个步骤:
1. 创建 HttpClient 的实例
2. 创建某种连接方法的实例,在这里是 GetMethod。在 GetMethod 的构造函数中传入待连接的地址
3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
4. 读 response
5. 释放连接。无论执行方法是否成功,都必须释放连接
6. 对得到后的内容进行处理
import java.io.IOException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.ProxyHost;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.client.ClientProtocolException;
/**
* @ClassName: ProxySample
* @Description: 测试HttpClient代理
* @author
* @date 2012-1-10 上午9:45:10
* @version V1.0
*/
public class ProxySample {
/**
* @Title: main
* @Description: 测试HttpClient代理
* @param args
* @author
* @date 2012-1-10
*/
public static void main(String[] args) {
// 创建 HttpClient 的实例
HttpClient httpClient = new HttpClient();
// 代理的主机
ProxyHost proxy = new ProxyHost("openproxy.huawei.com", 8080);
// 使用代理
httpClient.getHostConfiguration().setProxyHost(proxy);
// 创建Get连接方法的实例
HttpMethod getMethod = new GetMethod("http://www.apache.org");
// 使用系统提供的默认的恢复策略
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
try {
// 请求URI
System.out.println("executing request " + getMethod.getURI());
// 执行getMethod
int status = httpClient.executeMethod(getMethod);
System.out.println("status:" + status);
// 连接返回的状态码
if (HttpStatus.SC_OK == status) {
System.out.println("Connection to " + getMethod.getURI()
+ " Success!");
// 获取到的内容
String responseBody = getMethod.getResponseBodyAsString();
System.out.println(responseBody);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (URIException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放连接
getMethod.abort();
}
}
}