Android httpclient 登录并使用 cookie 进行进一步处理
Posted
技术标签:
【中文标题】Android httpclient 登录并使用 cookie 进行进一步处理【英文标题】:Android httpclient login and use cookies for further processes 【发布时间】:2012-12-25 20:20:09 【问题描述】:我正在开发一个包含登录活动和主要活动的应用程序。 如果用户第一次登录,应用程序会保存用户名并传入 sharedPrefs。并且在下一次启动时,登录活动使用这些用户名和密码,如果服务器返回 true(在 xml 中,getEntity)主要活动意图开始。登录后,我想使用启动登录中设置的 cookie 与网页交互。据我在网上搜索,他们说我应该使用相同的 httpclient 以免丢失 cookie。我试过了,但无法管理。那么,我可以不使用相同的 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?
提前致谢!
【问题讨论】:
【参考方案1】:您可以考虑通过这样的 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()。
如果还不够,你可以自己管理cookies,BasicCookieStore类是一个很好的起点,你可以查看这个线程: android BasicCookieStore, Cookies and HttpGet
希望对你有帮助。
【讨论】:
如何使用“MyAppHttpClient.INSTANCE.getConfiguredHttpClient()”定义一个新的 HttpClient?我试过这种方法,但没有用: DefaultHttpClient htpost = MyAppHttpClient.INSTANCE.getConfiguredHttpClient(); 在 try 块之间,“configuredHttpClient”的赋值在哪里?它保持空值,你能再更新一下代码吗? 可以这样使用:HttpClient httpclient = ClaimHttpClient.INSTANCE.getHttpClient(); HttpGet httpget = new HttpGet(someUrl); HttpResponse 响应 = httpclient.execute(httpget); 对不起,我已经更新了代码,try 块的最后一行已更改为:configuredHttpClient = new DefaultHttpClient(params); 谢谢。有用。但是,如果我尝试执行新的 httpget,就会出错。错误是:SingleClientConnManager(1402):SingleClientConnManager 的使用无效:连接仍然分配。我怎样才能避免这种情况发生?以上是关于Android httpclient 登录并使用 cookie 进行进一步处理的主要内容,如果未能解决你的问题,请参考以下文章
android 用httpclient登录无法保持会话状态 最后两次请求的cookie都不一样!我明明设成一样了?