参考网址:http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html
1. 读取网页(HTTP/HTTPS)内容
package http.demo;
import java.io.IOException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
/**
*最简单的HTTP客户端,用来演示通过GET或者POST方式访问某个页面
*/
public class SimpleClient {
public static void main(String[] args) throws IOException
{
HttpClient client = new HttpClient();
// 设置代理服务器地址和端口
//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);
// 使用 GET 方法 ,如果服务器需要通过 HTTPS 连接,那只需要将下面 URL 中的 http 换成 https
HttpMethod method =new GetMethod("http://java.sun.com");
//使用POST方法
//HttpMethod method = new PostMethod("http://java.sun.com");
client.executeMethod(method);
//打印服务器返回的状态
System.out.println(method.getStatusLine());
//打印返回的信息
System.out.println(method.getResponseBodyAsString());
//释放连接
method.releaseConnection();
}
}
首先创建一个HTTP客户端(HttpClient)的实例,然后选择提交的方法是GET或者POST,最后在HttpClient实例上执行提交的方法,最后从所选择的提交方法中读取服务器反馈回来的结果。
2. HttpClient工具类
public static String doPost(String url, NameValuePair[] params) {
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.addParameters(params);
postMethod.getParams().setParameter(
HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
try {
int statusCode = httpClient.executeMethod(postMethod);
String postResult = null;
if (200 == statusCode) {
postResult = postMethod.getResponseBodyAsString();
}
return postResult;
} catch (HttpException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
postMethod.releaseConnection();
}
return null;
}
支持httpclient3