2014-07-22 73 views
0

我已閱讀我可以找到的所有相關帖子,但仍無法解決我的問題。我的應用程序使用會話cookie與服務器通信,該會話cookie存儲爲org.apache.http.cookie.Cookie對象。我爲我的連接使用了HttpClient,它工作正常。如何爲HttpUrlConnection設置Cookie

授權:

 List<Cookie> cookies = httpclient.getCookieStore().getCookies(); 
     if (!cookies.isEmpty()) { 
      sessionCookie = cookies.get(0); 
      /** multiple cookies usage can be implemented if needed */ 
     } 

每個POST到服務器:

 CookieStore store = client.getCookieStore(); 
     HttpContext ctx = new BasicHttpContext(); 
     store.addCookie(Tools.getSessionCookie()); 
     ctx.setAttribute(ClientContext.COOKIE_STORE, store); 

我還挺新的,當涉及到Cookie,但我能注意到Cookie對象的外觀(至少在我看來)有點類似於JSONObject,有多個鍵值。現在我試圖使用LazyList將許多圖像加載到GridView。望着ImageLoader類我想通了,它採用了HttpUrlConnection

private Bitmap getBitmap(String url) { 
    File f = fileCache.getFile(url); 
    // from SD cache 
    Bitmap b = decodeFile(f); 
    if (b != null) 
     return b; 

    // from web 
    try { 
     Bitmap bitmap = null; 
     URL imageUrl = new URL(url); 
     HttpURLConnection conn = (HttpURLConnection) imageUrl 
       .openConnection(); 
     //timeouts modified 
     conn.setConnectTimeout(GetSettings.getTimeout(context, 
       AppConstants.FLAG_CONN_TIMEOUT)); 
     conn.setReadTimeout(GetSettings.getTimeout(context, 
       AppConstants.FLAG_SO_TIMEOUT)); 
     conn.setInstanceFollowRedirects(true); 
     InputStream is = conn.getInputStream(); 
     OutputStream os = new FileOutputStream(f); 
     Utils.CopyStream(is, os); 
     os.close(); 
     conn.disconnect(); 
     bitmap = decodeFile(f); 
     return bitmap; 
    } catch (Throwable ex) { 
     ex.printStackTrace(); 
     if (ex instanceof OutOfMemoryError) 
      memoryCache.clear(); 
     return null; 
    } 
} 

我無法修改設置會話cookie,當然我得到401 unauthorized作爲服務器響應。所以基本上我所擁有的是一個org.apache.http.cookie.Cookie對象。我試過conn.setRequestProperty("Cookie", mySessionCookie.getValue());但它沒有工作

什麼是在我的情況下使用會話cookie的正確方法是什麼?

回答

0

我最終修改了ImageLoader類,它現在使用的方式是HttpClient。不過,我仍在尋找一種使用HttpUrlConnection設置會話cookie的方法,因此我不會將自己的答案標記爲已接受。