HttpClient学习笔记一

来源:互联网 发布:未知数据库连接器错误 编辑:程序博客网 时间:2024/06/11 07:11
对 HttpClient是第一次接触,了解的不是太多。
但是感觉它的功能还是挺强大的:可以模拟一个浏览器去和一个服务器交互。
我的需求是自动从一个网站上下载数据。这样HttpClient解决了我的难题。
从网上看看搜索结果,口碑还是不错的。

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议

先看看官方提供的tutorial

大概的使用步骤:
  1. Create an instance of HttpClient.
  2. Create an instance of one of the methods (GetMethod in this case). The URL to connect to is passed in to the the method constructor.
  3. Tell HttpClient to execute the method.
  4. Read the response.
  5. Release the connection.
  6. Deal with the response.
提供的一个小例子:

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

public class HttpClientTutorial {

private static String url = "http://www.apache.org/";

public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();

// Create a method instance.
GetMethod method = new GetMethod(url);

// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));

try {
// Execute the method.
int statusCode = client.executeMethod(method);

if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}

// Read the response body.
byte[] responseBody = method.getResponseBody();

// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));

} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}


}