在 Android 上处理 HttpClient 的最佳方法是什么?
我可以找到大量教程,展示如何在简单的情况下构建和使用 HttpClient。但我找不到任何适合更复杂案例的合适文档。
在我的应用程序中,我有很多 Activity,每个 Activity 都必须能够使用 HTTPS 通过 POST 消息与远程 WebService 进行通信。我还必须登录这个服务,所以我需要管理登录cookie。
目前,我为 .onStart() 中的每个 Activity 构造一个单独的 HttpClient,并在 .onStop() 中释放它。我有一个工作队列,其中包含描述必须与远程服务通信的任务详细信息的对象。我使用单个工作线程 AsyncTask 执行这些任务。这个解决方案似乎有效,但我不确定它是不是最好的解决方案。
我考虑过另外两种架构:
- 创建一个处理 HttpClient 的后台服务。这样我就可以通过多个活动使用同一个实例,我想这会更好。但我不确定何时停止此服务并释放 HttpClient。
- 仅在需要时创建 HttpClient。例如,当用户单击启动远程调用的按钮时,我会构建客户端,设置 cookie 和 POST 消息,执行它,完成后我立即释放它。我认为这种方法非常糟糕,因为创建这样一个客户端会产生很大的开销(特别是如果我使用 HTTPS)。
因此,如果有人对 HttpClient 的工作原理以及在 Android 中应如何处理它有更多的了解,您能否对这些方法发表评论/分享一些有用的技巧?
谢谢
I can find loads of tutorials that show how should a HttpClient constructed and used in a simple case. But I fail to find any decent documentation for more complex cases.
In my app, I have a bunch of Activities, and each has to be able to communicate with a remote WebService with POST messages using HTTPS. I also have to log in to this service, so I need to manage the login cookie.
Currently, I construct a separate HttpClient for every single Activity in .onStart(), and releasing it in .onStop(). I have a work-queue that contains the objects describing the details of a task that has to communicate with the remote service. I execute these tasks using a single worker AsyncTask. This solution seems to work, but I'm just not sure that it's the most optimal one.
I've thought about 2 other architectures:
- Creating a background Service that handles the HttpClient. This way I might be able to use the same instance thru multiple Activities, and I guess this'd be better. But I'm not sure when to stop this Service and release the HttpClient.
- Create a HttpClient only when needed. So for example when the user clicks a button that initiates a remote call, then I construct the client, set up the cookies and the POST message, execute it, and when it's done I immediately release it. I think this approach is quite bad because of the overhead involved in creating such a client (especially if I use HTTPS).
So anybody that has more insight about the workings of HttpClient and how it should be treated in Android, could you please comment on these approches / share some useful tips?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决方案1很好。一旦队列为空,您就可以停止服务。它与解决方案 2 相结合,因为该服务仅在需要时启动。当您的用户单击按钮时,您将启动您的服务,例如您绑定到它并向其发出您的请求。
solution 1 is good. You can stop your service once your queue is empty. It combines with your solution 2 in that that the service is started only when needed. When your user clicks a button, you start your service, and for instance you bind to it and give it your request.
异步任务。在Google上搜索一个名为GrabURl的方法。
Asynctask. Search on Google a method called GrabURl.