Java 如何在Android上的活动之间在HttpContext中保存HTTP会话cookie?

Java 如何在Android上的活动之间在HttpContext中保存HTTP会话cookie?,java,android,http,session,keep-alive,Java,Android,Http,Session,Keep Alive,以下是当前我的应用程序的简单描述。它使用一些远程服务器API,它使用标准HTTP会话。 登录活动。它调用auth类,传递登录名和密码 public class Auth extends AsyncTask{ ... private DefaultHttpClient client = new DefaultHttpClient(); private HttpContext localContext = new BasicHttpContext(); private CookieStore coo

以下是当前我的应用程序的简单描述。它使用一些远程服务器API,它使用标准HTTP会话。 登录活动。它调用auth类,传递登录名和密码

public class Auth extends AsyncTask{
...
private DefaultHttpClient client = new DefaultHttpClient();
private HttpContext localContext = new BasicHttpContext();
private CookieStore cookieStore = new BasicCookieStore();
...
public void auth(String login, String password) {
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    HttpPost request = new HttpPost(url);
    ...
}
protected void onPostExecute(Boolean result){
    parent.loginresponse(result)
}
成功身份验证后,远程服务器将创建标准HTTP会话,并向我发送保存在CookiStore中的cookie。登录后,loginresponse启动主活动。在那里,我希望为所有API请求提供一个通用类


如何使登录后创建的HTTP会话信息在所有活动之间保持活动状态,并将其传递给相应API方法所需的函数

HttpClient client = getNewHttpClient();
        // Create a local instance of cookie store
        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);
        try {
            request = new HttpPost(url);
            // request.addHeader("Accept-Encoding", "gzip");
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (postParameters != null && postParameters.isEmpty() == false) {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    postParameters.size());
            String k, v;
            Iterator<String> itKeys = postParameters.keySet().iterator();
            while (itKeys.hasNext()) {
                k = itKeys.next();
                v = postParameters.get(k);
                nameValuePairs.add(new BasicNameValuePair(k, v));
            }

            UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(
                    nameValuePairs);
            request.setEntity(urlEntity);

        }
        try {

            Response = client.execute(request, localContext);
            HttpEntity entity = Response.getEntity();
            int statusCode = Response.getStatusLine().getStatusCode();
            Log.i(TAG, "" + statusCode);

            Log.i(TAG, "------------------------------------------------");

            if (entity != null) {
                Log.i(TAG,
                        "Response content length:" + entity.getContentLength());

            }
            List<Cookie> cookies = cookieStore.getCookies();
            for (int i = 0; i < cookies.size(); i++) {
                Log.i(TAG, "Local cookie: " + cookies.get(i));

            }

            try {
                InputStream in = (InputStream) entity.getContent();
                // Header contentEncoding =
                // Response.getFirstHeader("Content-Encoding");
                /*
                 * if (contentEncoding != null &&
                 * contentEncoding.getValue().equalsIgnoreCase("gzip")) { in =
                 * new GZIPInputStream(in); }
                 */
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(in));
                StringBuilder str = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {

                    Log.i(TAG, "" + str.append(line + "\n"));
                }
                in.close();
                response = str.toString();
                Log.i(TAG, "response" + response);
            } catch (IllegalStateException exc) {

                exc.printStackTrace();
            }

        } catch (Exception e) {

            Log.e("log_tag", "Error in http connection " + response);

        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            // client.getConnectionManager().shutdown();
        }

        return response;
    enter code here
HttpClient=getNewHttpClient();
//创建cookie存储的本地实例
CookieStore CookieStore=新的BasicCookieStore();
//创建本地HTTP上下文
HttpContext localContext=新的BasicHttpContext();
//将自定义cookie存储绑定到本地上下文
setAttribute(ClientContext.COOKIE_存储,cookieStore);
试一试{
请求=新的HttpPost(url);
//addHeader(“接受编码”、“gzip”);
}捕获(例外e){
e、 printStackTrace();
}
if(postParameters!=null&&postParameters.isEmpty()==false){
List name valuepairs=new ArrayList(
postParameters.size());
串k,v;
迭代器itKeys=postParameters.keySet().Iterator();
while(itKeys.hasNext()){
k=itKeys.next();
v=后参数get(k);
添加(新的BasicNameValuePair(k,v));
}
UrlEncodedFormEntity urlEntity=新UrlEncodedFormEntity(
名称(对);
request.setEntity(urlEntity);
}
试一试{
Response=client.execute(请求、本地上下文);
HttpEntity=Response.getEntity();
int statusCode=Response.getStatusLine().getStatusCode();
Log.i(标记“+”状态代码);
Log.i(标记“------------------------------------------------------------”);
如果(实体!=null){
Log.i(标签,
“响应内容长度:”+entity.getContentLength());
}
List cookies=cookieStore.getCookies();
对于(int i=0;i
如果您使用像这样的DI框架,您可以在活动之间维护一个
HttpContext
,并将其注入到任何您喜欢的地方

您可以使用如下所示的单例类:

public class UserSession
{
    private static UserSession sUserSession;

    /*
       The rest of your class declarations...
    */

    public get(){
        if (sUserSession == null)
        {
            sUserSession = new UserSession();
        }
        return sUserSession;
    }
}

初始化此类的实例后,它将保留在内存中。

最后,在和中找到了解决方案