7

这是我的应用程序当前的简单描述。它使用一些使用标准 HTTP 会话的远程服务器 API。登录活动。它调用 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 方法所需的函数?

4

3 回答 3

1

如果你使用像Dagger这样的 DI 框架,你可以维护一个HttpContextbetween Activity 并在任何你喜欢的地方注入它!

于 2014-11-28T12:05:30.660 回答
1

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

public class UserSession
{
    private static UserSession sUserSession;

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

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

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

于 2017-06-19T20:59:01.917 回答
0

您可以执行以下操作:

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
于 2012-05-24T13:19:38.087 回答