【问题标题】:Keep cookie session on android with httpclient使用 httpclient 在 android 上保持 cookie 会话
【发布时间】:2014-04-16 13:00:22
【问题描述】:

您好,我正在使用单独的 HttpClient 实例和 HttpResponce 实例进行多个 http 调用并从服务器获取响应。问题是我无法存储 cookie,并且每次我在登录后发出请求时,都会返回“身份验证错误:无法响应任何这些挑战”。如何为我的用例存储 cookie?代码如下:

public class MyHttpClient {

private DefaultHttpClient httpClient = new DefaultHttpClient();

    private CookieStore cookieStore = new BasicCookieStore();
    BasicHttpContext localContext = new BasicHttpContext();


 public MyHttpResponse get(String url) throws IOException{
          cookieStore = httpClient.getCookieStore();
          localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
      HttpGet httpGet = new HttpGet(url);
      return new MyHttpResponse(httpClient.execute(httpGet, localContext));

}

public MyhttpResponse post(String url, Arraylist<String> params ) throws IOException{
     cookieStore = httpClient.getCookieStore();
     localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
     HttpPost httpPost = new HttpPost(url);
     /* put params */
 return new MyHttpResponse(httpClient.execute(httpPost, localContext));

}

而 MyResponse 得到响应正文:

   if(response.getEntity() != null){
        InputStream lineStream = response.getEntity().getContent();

【问题讨论】:

    标签: android cookies httpclient


    【解决方案1】:

    试试这个:

    CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance(); 
    cookieManager.setAcceptCookie(true);
    cookieManager.setCookie(url,value);
    cookieSyncManager.sync();
    

    【讨论】:

      【解决方案2】:

      在将我的 httpClient 设置为 Singleton 后,我让它工作了。我不知道这是否是在整个应用程序中保持会话的最佳解决方案,但它正在工作。

      【讨论】:

      • 如果你想从一个字符串创建一个 cookie 存储(例如,如果你持久化 cookie 或者你不使用 httpClient 作为单例)看看这个答案stackoverflow.com/a/15924948/1714030
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 2013-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 2012-11-01
      相关资源
      最近更新 更多