2011-12-15 105 views
0

我要編寫一個Java程序,該程序部分解析需要用戶事先登錄的200個唯一頁面。我已經使用Chrome的開發者控制檯來確定我的特定登錄URL(https://r.espn.go.com/members/v3_1/login),驗證登錄過程是否使用POST請求,以及我的用戶名(用戶名)和密碼(密碼)的表單數據名稱。當使用this作者指定的方法爲後續請求檢索SESSIONID cookie時,返回的標頭大不相同,並且不返回cookie。使用Jsoup檢索sessionId cookies的問題

我也嘗試下面的代碼片段,它使用兩個Jsoup和Apache的HttpClient的,HttpPost和HttpResponse對象返回的loginpage:

MultipartEntity entity = new MultipartEntity(); 
entity.addPart("username", new StringBody(myUsername)); 
entity.addPart("password", new StringBody(myPassword)); 

HttpPost post = new HttpPost(url); 
post.setEntity(entity); 

HttpClient client = new DefaultHttpClient(); 
HttpResponse response = client.execute(post); 

String html = EntityUtils.toString(response.getEntity()); 

Document document = Jsoup.parse(html, url); 

我讀過的每個實例有一個登錄URL以.php後綴,這種方法只適用於基於PHP的登錄服務嗎?或者我在做一些根本性錯誤?

謝謝!

回答

1

讓HttpClient爲您管理cookies/session。發生這種情況

  1. 創建一個HttpContext並將其用於每個請求,以便會話/ cookie管理處於活動狀態。
  2. 設置的cookie存儲
  3. Exucute您在步驟1

下面是HttpClient的4.1.x的版本的示例代碼創建的上下文中的每個Web請求。請閱讀Section 3.8 HTTP state management and execution context的文檔。另外,請通過this thread

//create the local context to be shared across multiple requests of the same session 
HttpContext localContext = new BasicHttpContext(); 

// Create a local instance of cookie store 
CookieStore cookieStore = new BasicCookieStore(); 

// Bind custom cookie store to the local context 
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); 

// execute the post within the context 
HttpResponse response = client.execute(post,localContext); 

如果這沒有解決問題,那麼使用Wireshark或Fiddler2來檢查HTTP請求和響應流量。