我想在 Android 手机上构建 REST 客户端。
REST 服务器公开了多种资源,例如(GET)
http://foo.bar/customer List of all customer
http://foo.bar/customer/4711 The customer with id 4711
http://foo.bar/customer/vip List of all VIP customer
http://foo.bar/company List of all companys
http://foo.bar/company/4711 The company with the ID 4711
http://foo.bar/company/vip List of all VIP companys
我(认为)我知道如何与 REST 服务器通信并获取我需要的信息。我将使用这样的 API 实现 REST 客户端类
public List<Customer> getCustomers();
public Customer getCustomer(final String id);
public List<Customer> getVipCustomer();
public List<Company> getCompanies();
public Customer getCompany(final String id);
public List<Customer> getVipCompanies();
参考演示文稿“开发 Android REST 客户端应用程序” 我了解到,在 Activity 的工作线程中处理 REST 请求并不是一个好主意。相反,我应该使用 Service API。
我喜欢拥有一个绑定到(本地)服务的 Singleton ServiceHelper 的想法,但我担心我没有正确理解服务概念。
目前我不明白如何将 REST 调用结果(在服务中异步完成)报告回调用者 Activity。我还想知道我是否需要一个服务来处理所有 REST 请求(具有不同的返回类型),或者是否需要为每个 REST 请求提供专用服务。
可能我还有许多其他理解问题,所以对我来说最好的事情是满足我的需求的示例应用程序。我的用例并不罕见,我希望有示例应用程序。
请让我知道吗?
任何其他为我指明正确实施方向的建议也很有帮助(Android API-Demo 与我的用例不匹配)。
提前致谢。
Klaus
编辑:在SO上找到的类似主题(发布此内容后)引导我走向我需要的方向(最小化复杂的“Dobjanschi模式”):
I want to build a REST Client on an android phone.
The REST server exposes several resources, e.g. (GET)
http://foo.bar/customer List of all customer
http://foo.bar/customer/4711 The customer with id 4711
http://foo.bar/customer/vip List of all VIP customer
http://foo.bar/company List of all companys
http://foo.bar/company/4711 The company with the ID 4711
http://foo.bar/company/vip List of all VIP companys
I (think) I know how to talk to the REST server and get the information I need. I would implement a REST Client class with an API like this
public List<Customer> getCustomers();
public Customer getCustomer(final String id);
public List<Customer> getVipCustomer();
public List<Company> getCompanies();
public Customer getCompany(final String id);
public List<Customer> getVipCompanies();
Referred to the presentation "Developing Android REST client applications" from Virgil Dobjanschi I learned that it is no good idea to handle the REST request in an Worker Thread of the Activity. Instead I should use the Service API.
I like the idea of having a Singleton ServiceHelper which binds to a (Local) Service but I am afraid that I did not understand the Service concept correct.
For now I do not understand how to report a REST call result (done asynchrounous in a Service) back to the caller Activity. I also wonder if I need ONE Service which handles all REST requests (with different return types) or if I need a dedicated service for each REST request.
Probably I have many other understanding problems so the best thing for me would be a sample application which meets my needs. My use case is not unusual and I hope there is in example application out there.
Would you please let me know!
Any other suggestions which points me in the correct implementation direction are also helpful (Android API-Demo does not match my use case).
Thanks in advance.
Klaus
EDIT: Similar Topics found on SO (after posting this) which lead me in the direction I need (minimizing the complex "Dobjanschi pattern"):
发布评论
评论(8)
概览
编辑:
任何感兴趣的人也可以考虑看看RESTful android 这可能会让你更好地了解它。
我从尝试实现 Doobjanschi 模型的经验中学到的是,并非所有内容都是一成不变的,他只是向您提供了概述执行此操作可能会因应用程序而异,但公式是:
遵循此想法 + 添加您自己的 = 快乐的 Android 应用程序
某些应用程序上的模型可能因要求而异,有些可能不需要 SyncAdapter 的帐户,其他可能使用 C2DM,这一个我最近工作的内容可能会帮助某人:
创建一个具有 Account 和 AccountManager 的应用程序
它将允许您使用 SyncAdapter 来同步您的数据。这已在 创建您自己的 SyncAdapter
创建一个 ContentProvider(如果它适合您的需求)
此抽象不仅允许您访问数据库,还允许您访问数据库。转到 ServiceHelper 来执行 REST 调用,因为它具有与 REST Arch 一对一的映射方法。
内容提供商| REST方法
查询---------------->获取
插入----------------> PUT
更新----------------> POST
删除----------------> DELETE
ServiceHelper Layering
这家伙基本上将启动一个服务,该服务使用您从 ContentProvider 传递的参数执行 Http(不一定是协议,但它是最常见的)REST 方法。我传递了从内容提供者上的 UriMatcher 获取的匹配整数,因此我知道要访问哪些 REST 资源,即
服务
被执行(我大部分时间使用 IntentService),并且它会使用从帮手,有什么用?请记住,服务在后台运行是很好的。
还要实现一个 BroadCastReceiver,以便当服务完成其工作时通知我注册此广播的活动并再次重新查询。我相信这最后一步不在维吉尔会议上,但我很确定这是一个很好的方法。
RESTMethod 类
获取参数、WS 资源(http://myservice.com/service/path)添加参数,准备好一切,执行调用,并保存响应。
如果需要 authtoken,您可以向 AccountManager 请求
如果由于鉴权导致服务调用失败,您可以使authtoken失效并重新进行鉴权以获取新的token。
最后,无论我基于匹配器创建处理器并传递响应,RESTMethod 都会为我提供 XML 或 JSON。
处理器
负责解析响应并将其插入本地。
示例应用程序?当然!
另外,如果您对测试应用程序感兴趣,您可以查看 Eli-G,它可能不是最好的例子,但它遵循服务 REST 方法,它是用 ServiceHelper、处理器、ContentProvider、Loader 和 Broadcast 构建的。
OverView
Edit:
Anyone interest also consider taking a look at RESTful android this might give you a better look about it.
What i learned from the experience on trying to implement the Dobjanschi Model, is that not everything is written in stone and he only give you the overview of what to do this might changed from app to app but the formula is:
Follow this ideas + Add your own = Happy Android application
The model on some apps may vary from requirement some might not need the Account for the SyncAdapter other might use C2DM, this one that i worked recently might help someone:
Create an application that have Account and AccountManager
It will allow you to use the SyncAdapter to synchronized your data. This have been discussed on Create your own SyncAdapter
Create a ContentProvider (if it suits your needs)
This abstraction allows you to not only access the database but goes to the ServiceHelper to execute REST calls as it has one-per-one Mapping method with the REST Arch.
Content Provider | REST Method
query ----------------> GET
insert ----------------> PUT
update ----------------> POST
delete ----------------> DELETE
ServiceHelper Layering
This guy will basicly start (a) service(s) that execute a Http(not necessarily the protocol but it's the most common) REST method with the parameters that you passed from the ContentProvider. I passed the match integer that is gotten from the UriMatcher on the content Provider so i know what REST resource to access, i.e.
The service
Gets executed (I use IntentService most of the time) and it goes to the RESTMethod with the params passed from the helper, what is it good for? well remember Service are good to run things in background.
Also implement a BroadCastReceiver so when the service is done with its work notify my Activity that registered this Broadcast and requery again. I believe this last step is not on Virgill Conference but I'm pretty sure is a good way to go.
RESTMethod class
Takes the parameters, the WS resource(http://myservice.com/service/path) adds the parameters,prepared everything, execute the call, and save the response.
If the authtoken is needed you can requested from the AccountManager
If the calling of the service failed because authentication, you can invalidate the authtoken and reauth to get a new token.
Finally the RESTMethod gives me either a XML or JSON no matter i create a processor based on the matcher and pass the response.
The processor
It's in charged of parsing the response and insert it locally.
A Sample Application? Of course!
Also if you are interesting on a test application you look at Eli-G, it might not be the best example but it follow the Service REST approach, it is built with ServiceHelper, Processor, ContentProvider, Loader, and Broadcast.
Android 编程有一个完整的章节(13.探索内容提供商)专门讨论“选项 B: Virgil 的 Google I/O 演讲中的“使用 ContentProvider API”。
强烈推荐。
Android 编程,作者:Zigurd Mednieks、Laird Dornin、G. Blake Meike 和 Masumi Nakamura。版权所有 2011 O'Reilly Media, Inc.,978-1-449-38969-7。
Programming Android has a complete chapter (13. Exploring Content Providers) dedicated to 'Option B: Use the ContentProvider API' from Virgil's Google I/O talk.
Highly recommended.
Programming Android by Zigurd Mednieks, Laird Dornin, G. Blake Meike, and Masumi Nakamura. Copyright 2011 O’Reilly Media, Inc., 978-1-449-38969-7.
Virgil Doobjanschi 的“开发 Android REST 客户端应用程序”引起了很多讨论,因为在会议期间或之后都没有提供源代码。
如果您知道更多实现,请评论。
"Developing Android REST client applications" by Virgil Dobjanschi led to much discussion, since no source code was presented during the session or was provided afterwards.
Please comment if you know more implementations.
我们开发了一个解决此问题的库:RoboSpice。
该库使用 Virgil Doobjanschi 和 尼尔·古德曼,但是我们提供完整的一体化解决方案:
将返回 POJO 的请求(例如:REST 请求)
请求他们是否还活着
如果他们不再活着,结果
他们的 UI 线程
结果
输入!
我们实际上正在寻找社区的反馈。
We have developped a library that adresses this issue : RoboSpice.
The library uses the "service approach" described by Virgil Dobjanschi and Neil Goodmann, but we offer a complete all-in-one solution that :
requests that will return POJOs (ex: REST requests)
request if they are still alive
result if they are not alive anymore
their UI Thread
results
typed !
We are actually looking for feedback from the community.
Retrofit 在这里可能非常有帮助,它通过非常简单的配置为您构建一个适配器,例如:
Retrofit 将您的 REST API 转换为 Java 接口。
RestAdapter 类生成 GitHubService 接口的实现。
GitHubService服务=restAdapter.create(GitHubService.class);
对生成的 GitHubService 的每次调用都会向远程 Web 服务器发出 HTTP 请求。
欲了解更多信息,请访问官方网站:http://square.github.io/retrofit/
注意:您从Retrofit获得的适配器
RestAdapter
不是从BaseAdapter
派生的,您应该以某种方式为它制作一个包装器,就像这个SO问题一样为什么在 ListFragment 中调用 setListAdapter 后我的 ListView 为空?< /a>
Retrofit could be very helpful here, it builds an Adapter for you from a very simple configuration like:
Retrofit turns your REST API into a Java interface.
The RestAdapter class generates an implementation of the GitHubService interface.
GitHubService service = restAdapter.create(GitHubService.class);
Each call on the generated GitHubService makes an HTTP request to the remote webserver.
for more information visit the official site: http://square.github.io/retrofit/
Note: the adapter
RestAdapter
you get from Retrofit is not derived fromBaseAdapter
you should make a wrapper for it somehow like this SO questionWhy is my ListView empty after calling setListAdapter inside ListFragment?
这有点晚了,但这里有一篇文章解释了演讲中的第一个模式:
http://www.codeproject.com/Articles/429997/Sample-Implementation-of-Virgil-Dobjanschis-Rest-p
我喜欢第一个模式的一点是其余方法的接口是一个普通类,内容提供程序仅用于提供对数据库的访问。
This is a little late but here is an article which explains the first pattern from the talk:
http://www.codeproject.com/Articles/429997/Sample-Implementation-of-Virgil-Dobjanschis-Rest-p
The thing I like about the first pattern is that the interface to the rest methods is a plain class, and the Content Provider is left to simply provide access to the database.
对于初学者,您应该查看 Google 官方 I/O 2010 应用的源代码,尤其是SyncService 以及 io 子包.
You should check out the source code for Google's official I/O 2010 app, for starters, particularly the SyncService and the various classes in the io subpackage.
好消息伙计们。
服务助手的实现可以在这里找到:https://github.com/MathiasSeguy-Android2EE/MythicServiceHelper
它是一个开源项目 (Apache 2)。
我正处于项目的开始阶段。我已经完成了一个项目,在其中定义了要执行的模式,但我还没有提取代码来创建一个干净的库。
很快就会完成。
Good news guys.
An implementation of the service helper is available here: https://github.com/MathiasSeguy-Android2EE/MythicServiceHelper
It's an open source project (Apache 2).
I am at the beginning of the project. I've done a project where I defined the pattern to do, but i haven't yet extract the code to make a clean librairy.
It will be done soon.