5

我在我的 Android 应用程序中使用 DefaultHttpClient 的单例实例,以便与我的网站的会话在登录后在多个活动中保持身份验证。

这是 DefaultHttpClient 的单例类:

public class Client {
  private static DefaultHttpClient instance = null;
  //handler for current response in UI thread after receiving it in AsyncTask
  private static HttpResponse currentResponse = null;

  //I also tried this without "synchronized"
  public synchronized static DefaultHttpClient getInstance()
  {
  if(instance == null)
    {
      instance = new DefaultHttpClient();
    }
    return instance;
  }
  public static void setCurrentResponse(HttpResponse response)
  {
    currentResponse = response;
  }
  public static HttpResponse getCurrentResponse()
  {
    return currentResponse;
  }
}

每次使用 Client.getInstance() 在 AsyncTask 中使用客户端时,我都会调用客户端。

我努力了:

ClientInstance = Client.getInstance();
Client.setCurrentResponse(ClientInstance.execute(HttpPost to execute));

我努力了:

Client.setCurrentResponse(Client.getInstance().execute(HttpPost to execute));

以及我通过搜索找到的许多其他方法。

我也尝试过使用 CookeStore 和 HttpContext,它们会产生相同的结果。

当我从响应中获取实体时,在实体上使用 consumeContent() 也不能解决问题。

我发现的所有内容都表明,使用 DefaultHttpClient 的单例实例允许它维持其会话,但每次我执行帖子以执行我的网站要求用户登录的操作时,我得到的响应正文显示指示未设置“user_id”会话变量的错误(因此用户未登录)。我已经彻底搜索了 Google 和 Stack Overflow,但无济于事。有人可以指出我做错了什么吗?

4

1 回答 1

6

Sorry for the question, guys.

After almost losing my sanity, I looked my php code over one more time. It turns out the problem was on my webpage - I was not allowing the php to call session_start() when receiving the mobile HttpPost. Who knows, maybe my question/answer will help somebody else.

于 2012-10-26T21:39:18.333 回答