我已阅读我可以找到的所有相关帖子,但仍无法解决我的问题。我的应用程序使用会话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的正确方法是什么?