English 中文(简体)
如何将 HTTP 会话 cookies 保存在 HttpContext 中, 在关于Android 的活动之间?
原标题:How to keep HTTP session cookies in HttpContext between activities on Android?

Here is current simple description my app. It uses some remote server API, which uses standart HTTP session. Login activity. It calls auth class, passing login and password.

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

成功验证时, 远程服务器创建了 sardart HTTP 会话, 发送给我 cookie, 保存在 CookiStore 中 。 登录后, 登录响应开始主活动 。 在那里, 我希望所有 API 请求都有一个通用类 。

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

问题回答

如果您使用 < a href=> "http://square.github.io/dagger/" rel="nofollow" > Dagger 这样的DI框架,您可以在活动之间保留 HtpContext , 并随你随心所欲地注入它!

您可以使用一个单吨级, 它会看起来类似 :

public class UserSession
{
    private static UserSession sUserSession;

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

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

此类的一例一旦初始化, 将留在记忆中 。

你可以做一些类似的事情,比如:

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




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签