2011-07-19 128 views
0

此方法用於消費我也控制的網絡服務。網絡服務設置cookie以保持用戶登錄。消費網絡服務和存儲cookies

這一切都通過瀏覽器正常工作。即我可以調用登錄URL,它會cookie我的瀏覽器,隨後訪問Web服務可以識別我的cookie。

在android中,我可以在登錄時獲得成功返回,但是Cookie似乎沒有設置。

您可以看到此代碼將cookie數據打印到輸出的位置。它在打印登錄腳本時打印該cookie,但後續調用該功能時,它不再識別cookie。

下面是我使用的代碼,我從一個例子別人開始貼:

private JSONObject getResponse(String func, List<NameValuePair> args) throws Exception { 

    HttpClient httpclient = new DefaultHttpClient(); 
    try { 
     // Create a local instance of cookie store 
     CookieStore cookieStore = new BasicCookieStore(); 

     // Create local HTTP context 
     HttpContext localContext = new BasicHttpContext(); 
     // Bind custom cookie store to the local context 
     localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); 

     HttpPost put= new HttpPost("http://example.com/api/" + func); 
     if (args != null) { 
      put.setEntity(new UrlEncodedFormEntity(args)); 
     } 

     System.out.println("executing request " + put.getURI()); 

     // Pass local context as a parameter 
     HttpResponse response = httpclient.execute(put, localContext); 
     HttpEntity entity = response.getEntity(); 

     System.out.println("----------------------------------------"); 
     System.out.println(response.getStatusLine()); 
     if (entity != null) { 
      System.out.println("Response content length: " + entity.getContentLength()); 
     } 
     List<Cookie> cookies = cookieStore.getCookies(); 
     for (int i = 0; i < cookies.size(); i++) { 
      System.out.println("Local cookie: " + cookies.get(i)); 
     } 

     // Consume response content 
     //EntityUtils.consume(entity); 
     System.out.println("----------------------------------------"); 

     InputStream instream = entity.getContent(); 
     String result = convertStreamToString(instream); 
     instream.close(); 
     entity.consumeContent(); 

     System.out.println("JSON Output: " + result); 

     return new JSONObject(result); 

    } finally { 
     // When HttpClient instance is no longer needed, 
     // shut down the connection manager to ensure 
     // immediate deallocation of all system resources 
     httpclient.getConnectionManager().shutdown(); 
    } 
} 

回答

3

這可能是因爲您的HttpClient和的CookieStore是局部的GETRESPONSE。儘量讓它們成爲全球性的,這樣它們可以堅持接下來的通話。

2

當您試圖訪問鎖定在一個網址內容叫你需要手動設置爲下一個到來的呼叫一個cookie,這是可以做到用:

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
httpURLConnection.setInstanceFollowRedirects(false); 

httpURLConnection.setRequestProperty("Host", domainOfYourCookie); 
httpURLConnection.setRequestProperty("Cookie", valueOfYourCookie); 

我已經寫了關於另外一個答案這個主題,你可以找到here