首页 文章

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

提问于
浏览
7

这是我的应用程序的当前简单描述 . 它使用一些远程服务器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会话,向我发送cookie,保存在CookiStore中 . 登录后,loginresponse启动主要活动 . 我希望在所有API请求中都有一个通用类 .

如何正确保存登录后创建的所有活动之间的HTTP会话信息,并将其传递给相应API方法所需的函数?

3 回答

  • 0

    如果您使用像Dagger这样的DI框架,您可以在活动之间维护 HttpContext 并将其注入任何您喜欢的地方!

  • 1

    您可以使用看起来像这样的单例类:

    public class UserSession
    {
        private static UserSession sUserSession;
    
        /*
           The rest of your class declarations...
        */
    
        public get(){
            if (sUserSession == null)
            {
                sUserSession = new UserSession();
            }
            return sUserSession;
        }
    }
    

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

  • 1

    您可以执行以下操作:

    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
    

相关问题