標籤:imp class eval index browser pac body 密碼 成功
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
public class TestLogin {
public static void main(String[] args) {
// 登陸 Url
String loginUrl = "http://139.196.40.80:3000/login";
// 需登陸後訪問的 Url
String dataUrl = "http://139.196.40.80:3000/index";
HttpClient httpClient = new HttpClient();
// 類比登陸,按實際伺服器端要求選用 Post 或 Get 請求方式
PostMethod postMethod = new PostMethod(loginUrl);
// 設定登陸時要求的資訊,使用者名稱和密碼
NameValuePair[] data = { new NameValuePair("username", "lixiuming"),
new NameValuePair("password", "lixiuming") };
postMethod.setRequestBody(data);
try {
// 設定 HttpClient 接收 Cookie,用與瀏覽器一樣的策略
httpClient.getParams().setCookiePolicy(
CookiePolicy.BROWSER_COMPATIBILITY);
httpClient.executeMethod(postMethod);
// 獲得登陸後的 Cookie
Cookie[] cookies = httpClient.getState().getCookies();
StringBuffer tmpcookies = new StringBuffer();
for (Cookie c : cookies) {
tmpcookies.append(c.toString() + ";");
}
// 進行登陸後的操作1581,1602,1603,1610,1609,1608,1607,1606,1605,1620,1619,1617,1616,1622,1626,1642,1648,1647,1657
GetMethod getMethod = new GetMethod(dataUrl);
// 每次訪問需授權的網址時需帶上前面的 cookie 作為通行證
getMethod.setRequestHeader("cookie", tmpcookies.toString());
// 你還可以通過 PostMethod/GetMethod 設定更多的請求後資料
// 例如,referer 從哪裡來的,UA 像搜尋引擎都會表名自己是誰,無良搜尋引擎除外
postMethod.setRequestHeader("Referer", "http://139.196.40.80:3000/index");
postMethod.setRequestHeader("User-Agent", "www Spot");
httpClient.executeMethod(getMethod);
// 列印出返回資料,檢驗一下是否成功
String text = getMethod.getResponseBodyAsString();
System.out.println(text);
} catch (Exception e) {
e.printStackTrace();
}
}
}
httpClient 保持session