一、POST请求:
private static void post(String url) {
PostMethod postMethod = null;
GetMethod getMethod = null;
String captchaCode = "0251";
String sessionId = "r0fud17p49zenksx97uzdre7";
try {
HttpClient client = new HttpClient();
postMethod = new PostMethod(url);
NameValuePair[] arr = new NameValuePair[3];
NameValuePair username = new NameValuePair("username","ppt");
arr[0] = username;
NameValuePair password = new NameValuePair("password","ppt");
arr[1] = password;
NameValuePair captcha = new NameValuePair("captcha",captchaCode);
arr[2] = captcha;
postMethod.setRequestHeader("Cookie", "JSESSIONID="+sessionId);
postMethod.setRequestBody(arr);
int status = client.executeMethod(postMethod);
if(status == HttpStatus.SC_MOVED_TEMPORARILY) {
Header[] header = postMethod.getResponseHeaders();
for(Header hh : header) {
String headerName = hh.getName();
if("Location".equals(headerName)) {
String value = hh.getValue();
getMethod = new GetMethod(value);
getMethod.setRequestHeader("Cookie", "JSESSIONID="+sessionId);
int statu = client.executeMethod(getMethod);
if(statu == HttpStatus.SC_OK) {
String str = getMethod.getResponseBodyAsString();
System.out.println(str);
}
}
}
}
if(status == HttpStatus.SC_OK) {
String content = postMethod.getResponseBodyAsString();
System.out.println(content);
} else {
System.out.println("http status: " + status);
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(postMethod != null) {
postMethod.releaseConnection();
}
if(getMethod != null) {
getMethod.releaseConnection();
}
}
}
二、GET 请求:
private static void get(String url) {
GetMethod method = null;
try {
HttpClient client = new HttpClient();
method = new GetMethod(url);
method.setRequestHeader("Cookie", "JSESSIONID=2D94ED969F39054DDB4444CFE24F550F");
int status = client.executeMethod(method);
if(status == HttpStatus.SC_OK) {
String content = method.getResponseBodyAsString();
System.out.println(content);
} else {
System.out.println("http status:" + status);
}
} catch(Exception e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
}