2012-12-25 33 views
4

我正在开发一个包含登录活动和主要活动的应用程序。 如果用户第一次登录,该应用会保存用户名并传入sharedPrefs。在下一次启动时,如果服务器返回true(在xml,getEntity中)主要活动意图开始,登录活动将使用这些用户名和密码。登录后,我想使用启动登录中设置的cookie与网页进行交互。就我通过网络进行搜索而言,他们说我应该使用相同的httpclient以避免丢失cookie。我试过了,但无法管理。那么,我可以在不使用同一个httpclient的情况下使用cookie吗?Android httpclient登录并使用Cookie进一步处理

我的应用程序的通用逻辑:

httpclient.execute("http://www.abc.com/index.php?process=login&user="+variable1+"&pass="+variable1); 

//here I get the entity of this response and I parse that return value, after that, if(login==true)--> go on... 
//here I have to read all page from website which is protected by user authentication(by cookies).(ex:index.php?process=getmymessages) 
//But I did not manage that. At this point what is your suggestions? 

提前感谢!

回答

3

可以考虑通过一个Singleton解决这样使用相同的HttpClient:

public enum MyAppHttpClient { 
    INSTANCE; 

    private HttpClient configuredHttpClient = null; 

    public HttpClient getConfiguredHttpClient() { 
     if (configuredHttpClient == null) { 
      try { 
       HttpParams params = new BasicHttpParams(); 
       HttpConnectionParams.setConnectionTimeout(params, 5000); 
       HttpConnectionParams.setSoTimeout(params, 5000); 
       configuredHttpClient = new DefaultHttpClient(params); 
      } catch (Exception e) { 
       configuredHttpClient = new DefaultHttpClient(); 
      } 
     } 

     return configuredHttpClient; 
    } 
} 

你到处都可以调用MyAppHttpClient.INSTANCE.getConfiguredHttpClient()在你需要它。

如果这是不够的,你可以自己管理的饼干,BasicCookieStore类是一个很好的起点,你可以检查此线程: Android BasicCookieStore, Cookies and HttpGet

我希望它能帮助你。

+0

如何通过使用“MyAppHttpClient.INSTANCE.getConfiguredHttpClient()”来定义一个新的HttpClient?我试过这种方式,但它没有工作:DefaultHttpClient htpost = MyAppHttpClient.INSTANCE.getConfiguredHttpClient(); –

+0

尝试{}块之间,其中是“configuredHttpClient”分配的值?它维护空值,你可以再次更新代码吗? –

+0

你可以这样使用它: HttpClient httpclient = ClaimHttpClient.INSTANCE.getHttpClient(); HttpGet httpget = new HttpGet(someUrl); HttpResponse response = httpclient.execute(httpget); – peekler