AndroidHttpClient和Cookies

ben*_*dev 0 cookies android httpclient httpcontext

使用带有cookie的AndroidHttpClient给我混合200 ok和403禁止响应.我不确定我做错了什么.

我以下列方式使用AndroidHttpClient:

我有几个后台线程类,每个类都执行以下操作:

HttpGet get...
HttpClient client = AndroidHttpClient.newInstance("Android");
HttpContext http_context = HttpSupport.getHttpContextInstance(); 
CookieStore cookie_store = HttpSupport.getCookieStoreInstance();
http_context.setAttribute(ClientContext.COOKIE_STORE, cookie_store);
client.execute(
Run Code Online (Sandbox Code Playgroud)

HttpSupport是一个包含两个静态字段的类; 一个CookieStore和一个HttpContext:

public class HttpSupport {

private static HttpContext _context;
private static CookieStore _cookieStore;

public static synchronized HttpContext getHttpContextInstance() {
    if (_context == null) {
        _context = new BasicHttpContext();
    }
    return _context;
}

public static synchronized CookieStore getCookieStoreInstance() {
    if (_cookieStore == null) {
        _cookieStore = new BasicCookieStore();
    }
    return _cookieStore;
}

}
Run Code Online (Sandbox Code Playgroud)

在应用程序中有多个AndroidHttpClient实例可以吗?我是否正确存储了cookie?

Mat*_*lfe 5

我建议使用Android异步HTTP客户端

它实现了自己的持久性cookie存储(PersistentCookieStore),它非常易于使用.事实上,如果您不想将库用于其异步功能,您可以将它用于它提供的持久Cookie存储.但是它的异步功能非常值得.

因此,要将它与当前类一起使用,您只需在HttpSupport类中进行更改即可

public static synchronized CookieStore getCookieStoreInstance(Context context) {
    if (_cookieStore == null) {
        _cookieStore = new PersistentCookieStore(context);
    }
    return _cookieStore;
}
Run Code Online (Sandbox Code Playgroud)

请注意,您必须将方法的上下文添加到PersistentCookieStore才能工作.