java - HttpGet 是否自动处理 cookie?

标签 java android http cookies httpclient

我想在使用 HttpGet 连接到服务器时保留 session ,我需要了解它如何处理 cookie。

服务器开发人员说他自己处理所有 cookie 的东西。 我使用 HttpGet 请求访问服务器,如下所示: InputStream isResponse = null;

    HttpGet httpget = new HttpGet(strUrl);
    HttpResponse response = mClient.execute(httpget);

    HttpEntity entity = response.getEntity();
    isResponse = entity.getContent();
    responseBody = convertStreamToString(isResponse);

    return responseBody;
  1. 我应该做更多的事情吗?他是否自动将 cookie 放在我的设备上并且 HttpGet 方法知道使用它来保持使用 cookie 的 sessionID?

  2. 如何检查我的设备上是否存在 cookie,以便了解 session 是否“有效”?

  3. 如果我使用以下代码获取 cookie:

    CookieStore cookieStore = new BasicCookieStore();
    
    // Create local HTTP context
    HttpContext localContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    
    HttpGet httpget = new HttpGet(strUrl);
    HttpResponse response = mClient.execute(httpget,localContext);
    

HttpGet 是否仍像以前一样处理 cookie?

  1. 我看到 DefaultHttpClient(上面代码中的 mClient)有自己的 CookieStore。如何保存它的 cookie 并在我下次创建它时加载它们?

最佳答案

所以... 在绞尽脑汁想了几个小时并实现了我自己的原始 CookieStore 之后,我找到了 Android Asynchronous Http Client实现,其中包括一个很好用的 PersistentCookieStore! 只需将 jar 添加到我的项目并按如下方式使用它:

PersistentCookieStore cookieStore = new PersistentCookieStore(context);
DefaultHttpClient mClient = new DefaultHttpClient();    
mClient.setCookieStore(cookieStore);

就是这样!当应用程序再次打开时,Cookie 将被保存并重复使用。

谢谢 James Smith,无论您身在何处。你至少让一个男人开心了。

如果有人对我自己的原始实现(也有效)感兴趣:

package com.pinhassi.android.utilslib;

import java.util.Date;
import java.util.List;

import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class MyPersistentCookieStore extends BasicCookieStore {
private static final String COOKIES_LIST = "CookiesList";
private static final String COOKIES_NAMES = "CookiesNames";

private Context mContext;
/**
 * 
 */
public MyPersistentCookieStore(Context context) {
    super();
    mContext = context;
    load();
}

@Override
public synchronized void clear(){
    super.clear();
    save();
}

@Override
public synchronized boolean clearExpired(Date date){
    boolean res = super.clearExpired(date);
    save();
    return res;
}

@Override
public synchronized void addCookie(Cookie cookie){
    super.addCookie(cookie);
    save();
}

@Override
public synchronized void addCookies(Cookie[] cookie){
    super.addCookies(cookie);
    save();
}

public synchronized void save()
{
    Editor editor = mContext.getSharedPreferences(COOKIES_LIST, Context.MODE_PRIVATE).edit();
    editor.clear();
    List <Cookie> cookies = this.getCookies();
    StringBuilder sb = new StringBuilder();
    for (Cookie cookie : cookies)
    {
        editor.putString(cookie.getName(),cookie.getValue());
        sb.append(cookie.getName()+";");
    }
    editor.putString(COOKIES_NAMES,sb.toString());
    editor.commit();
}

public synchronized void load()
{
    SharedPreferences prefs = mContext.getSharedPreferences(COOKIES_LIST, Context.MODE_PRIVATE);
    String [] cookies = prefs.getString(COOKIES_NAMES,"").split(";");
    for (String cookieName : cookies){
        String cookieValue = prefs.getString(cookieName, null);
        if (cookieValue!=null)
            super.addCookie(new BasicClientCookie(cookieName,cookieValue));
    }

    }

}

关于java - HttpGet 是否自动处理 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7427489/

相关文章:

Angular : TypeError: Cannot read property 'length' of null when subscribe()

java - JPA 实体监听器中的排除字段

java - 使用另一个 Map <String, List<String>> 中的选择性元素创建一个新的 Map <String, List<String>>

android - onContextItemSelected 从未使用带有 ListView 的对话框调用

java - 为什么 Facebook 登录无法在 Android 中的签名版本 APK 中工作?

http - 任何人都可以提供有关 hash(#) 在 url 中的各种用途的好信息吗?

java - 在构造函数上使用具有规范的泛型

java - 从 2.10 升级时 Jackson 序列化失败(InvalidDefinitionException : Type id handling not implemented for type java. lang.Object)

android - 如何配置slf4j-android?

http - 为什么从磁盘缓存返回http 200代码,响应头中既没有过期也没有缓存控制?