2012-04-28 108 views
4

我可以使用org.apache.http.clien.HttpClient發送POST請求並獲取HTTP響應。但是我登錄時不能獲取HTML內容,因爲我的PHP腳本需要cookie。那麼,如何在POST請求之後讀取POST請求響應的cookie並使用GET請求發回它?如何從POST請求中檢索cookie?

HttpClient httpClient = new DefaultHttpClient(); 

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("username", "user")); 
    nameValuePairs.add(new BasicNameValuePair("password", "passwd")); 

    HttpPost httpPost = new HttpPost("http://localhost/index.php"); 
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

    HttpResponse httpResponse = httpClient.execute(httpPost); 

    BufferedInputStream bis = new BufferedInputStream(httpResponse.getEntity().getContent()); // Just gets the HTML content, not the cookies 

回答

8

的餅乾是一個標準的頭,這樣你就可以從

httpResponse.getHeader("Cookie") 

得到它,如果你作爲呼叫從同一個應用程序的服務器,可以讓HttpClient的保持Cookie狀態,而。不要每次都創建一個新的實例,它應該可以工作。

+0

String cookie = httpResponse.getFirstHeader(「Cookie」)。getValue(); – 2017-05-16 18:56:52