源自http://www.ibm.com/developerworks/cn/opensource/os-httpclient/
package com.xiva.test.httpclient;
import java.io.IOException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpClientMain {
private static HttpClient httpClient = new HttpClient();
public static void getMethodDemo() throws IOException {
GetMethod getMethod = new GetMethod("http://www.ibm.com/");
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
// 执行getMethod
int statusCode = 0;
try {
statusCode = httpClient.executeMethod(getMethod);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + getMethod.getStatusLine());
}
byte[] responseBody = getMethod.getResponseBody();
getMethod.releaseConnection();
System.out.println(new String(responseBody));
}
public static void postMethodDemo() throws IOException {
String url = "http://xiva.iteye.com/login";
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data = { new NameValuePair("authenticity_token", "ByoUb/Sn49tKYhCobMHFXUFnGSEtshm9F70naUAkdms="),
new NameValuePair("name", ""),
new NameValuePair("password", ""),
new NameValuePair("button", "登 录") };
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
// 执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
// 301或者302
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
// 从头中取出转向的地址
Header locationHeader = postMethod.getResponseHeader("location");
String location = null;
if (locationHeader != null) {
location = locationHeader.getValue();
System.out.println("The page was redirected to:" + location);
} else {
System.err.println("Location field value is null.");
}
return;
}
else
{
byte[] responseBody = postMethod.getResponseBody();
System.out.println(statusCode);
System.out.println(new String(responseBody));
}
}
public static void main(String[] args) throws IOException {
// getMethodDemo();
postMethodDemo();
}
}
http://mirror.bjtu.edu.cn/apache//james/mime4j/apache-mime4j-0.7.2-bin.zip