有人知道如何使用 com.android.volley 库将 session cookie 附加到请求中吗? 当我登录到一个网站时,它会给我一个 session cookie。浏览器会将该 cookie 与任何后续请求一起发回。 Volley 似乎不会这样做,至少不会自动这样做。
谢谢。
最佳答案
Volley 本身并不实际发出 HTTP 请求,因此不直接管理 Cookie。它改为使用 HttpStack 的实例来执行此操作。主要有两种实现方式:
- HurlStack:在后台使用 HttpUrlConnection
- HttpClientStack:在后台使用 Apache HttpClient
Cookie 管理是那些 HttpStacks 的责任。他们各自处理 Cookie 的方式不同。
如果你需要支持<2.3,那么你应该使用HttpClientStack:
配置一个 HttpClient 实例,并将其传递给 Volley 以供其在后台使用:
// If you need to directly manipulate cookies later on, hold onto this client
// object as it gives you access to the Cookie Store
DefaultHttpClient httpclient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
httpclient.setCookieStore( cookieStore );
HttpStack httpStack = new HttpClientStack( httpclient );
RequestQueue requestQueue = Volley.newRequestQueue( context, httpStack );
与手动将 cookie 插入标题相比,这样做的优势在于您可以获得实际的 cookie 管理。您商店中的 Cookie 将正确响应过期或更新它们的 HTTP 控件。
我更进一步,将 BasicCookieStore 子类化,这样我就可以自动将我的 cookie 保存到磁盘。
但是!如果您不需要需要支持旧版本的 Android。只需使用此方法:
// CookieStore is just an interface, you can implement it and do things like
// save the cookies to disk or what ever.
CookieStore cookieStore = new MyCookieStore();
CookieManager manager = new CookieManager( cookieStore, CookiePolicy.ACCEPT_ALL );
CookieHandler.setDefault( manager );
// Optionally, you can just use the default CookieManager
CookieManager manager = new CookieManager();
CookieHandler.setDefault( manager );
HttpURLConnection 将隐式查询 CookieManager。 HttpUrlConnection 也更高效,更易于实现和使用 IMO。
关于android - 在 Android volley 库中使用 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16680701/