HttpGet 会自动处理 cookie 吗?

发布于 2024-12-04 13:47:36 字数 1101 浏览 1 评论 0原文

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

服务器开发人员说他自己处理所有cookies。 我使用 HttpGet 请求访问服务器,如下所示: 输入流 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 是否存在于我的设备上,以便了解会话是否“有效”?

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

    CookieStore cookieStore = new BasicCookieStore();
    
    // 创建本地 HTTP 上下文
    HttpContext localContext = new BasicHttpContext();
    // 将自定义 cookie 存储绑定到本地上下文
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    
    HttpGet httpget = new HttpGet(strUrl);
    HttpResponse 响应 = mClient.execute(httpget,localContext);
    

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

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

I would like to preserve a session while connecting to server using HttpGet and I need to understand how it handles cookies.

The server developer says that he handles all cookies stuff by himself.
I use HttpGet request to access the server as follows:
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. Should I do something more? Does he put the cookie on my device automatically and the HttpGet method knows to use it in order to keep the sessionID using the cookie?

  2. How can I check if the cookie exist on my device, in order to know if the session is "alive"?

  3. In case I use the following code to get the 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);
    

does the HttpGet still handles the cookies the same as before?

  1. I see that DefaultHttpClient (mClient in the code above) has its own CookieStore. How can I save its cookies and load them next time I create it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

简单气质女生网名 2024-12-11 13:47:36

所以...
经过几个小时的绞尽脑汁并实现了我自己的原始 CookieStore 后,我发现了 Android 异步 Http 客户端 实现,其中包括一个很好用的持久CookieStore!
只需将 jar 添加到我的项目中并按如下方式使用它:

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

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

谢谢詹姆斯·史密斯,无论你在哪里。你至少让一个人开心了。

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

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));
    }

    }

}

So...
After cracking my head for hours and implementing my own primitive CookieStore, I found Android Asynchronous Http Client implementation, that includes a nice PersistentCookieStore that works great!
Simply added the jar to my project and used it as follows:

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

and that's it! The cookies are saved and reused when the application is open again.

Thank you James Smith, where ever you are. You made at least one man happy.

If anyone interested in my own primitive implementation (that also works) here it is:

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));
    }

    }

}
生活了然无味 2024-12-11 13:47:36

不,cookie 不会自动处理。要自动保存cookie,请使用
BasicCookeStore

有关使用的更多信息如下: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html

另请参阅此答案:Android HttpClient 持久 cookies

No, cookies are not handled automatically. To save cookies automatically use
BasicCookeStore

More info on usage is here: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html

Also see this answer: Android HttpClient persistent cookies

绮筵 2024-12-11 13:47:36

我不必关心cookies。当我创建 DefaultHttpClient 并执行 httpclient.execute(httpget); 作为 此处对象在其上存储会话。因此,首先我进行登录,然后我可以使用 API 的私有函数。如果我想注销,我可以创建对象 DefaultHttpClient 的新实例或调用注销函数。

因此,如果您想使用 cookie 的信息,请使用 CookieStore,如果不只是使用单例实例来保持对象 DefaultHttpClient

I haven't had to care about cookies. When I create my DefaultHttpClient and do the httpclient.execute(httpget); as here the object stores the session on it. So first I do the login and later I can use the private functions of my API. If I want to logout, I create a new instance of my object DefaultHttpClient or call the logout function.

So in case you want to use the cookie's information use the CookieStore, if not just use a singleton instance to keep alive the object DefaultHttpClient

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文