需要实现 Virgil Doobjanschi REST 实现模式的示例 Android REST 客户端项目

发布于 2024-10-16 15:34:56 字数 1762 浏览 2 评论 0 原文

我想在 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"):

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

開玄 2024-10-23 15:34:56

概览

编辑:

任何感兴趣的人也可以考虑看看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 资源,即

class ServiceHelper{

    public static void execute(Context context,int match,String parameters){
//find the service resource (/path/to/remote/service with the match
//start service with parameters 
    }

}

服务

被执行(我大部分时间使用 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.

class ServiceHelper{

    public static void execute(Context context,int match,String parameters){
//find the service resource (/path/to/remote/service with the match
//start service with parameters 
    }

}

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.

晨敛清荷 2024-10-23 15:34:56

Android 编程有一个完整的章节(13.探索内容提供商)专门讨论“选项 B: Virgil 的 Google I/O 演讲中的“使用 ContentProvider API”。

我们并不是唯一看到这种方法好处的人。在 2010 年 5 月的 Google I/O 大会上,Google 的 Virgil Doobjanschi 发表了一场演讲,概述了以下使用内容提供商将 RESTful Web 服务集成到 Android 应用程序中的三种模式...

在本章中,我们将通过第二个 Finch 视频示例详细探讨第二种模式;该策略将为您的应用程序带来许多重要的好处。由于这种方法将网络操作优雅地集成到 Android MVC 中,我们给它起了个绰号“网络 MVC”。

Android 编程的未来版本可能会解决其他两种方法,并记录此 Google 演示文稿的更多详细信息。读完本章后,我们建议您查看 Google 的演讲。

强烈推荐。

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.

We are not the only ones who see the benefits of this approach. At the Google I/O conference in May 2010, Virgil Dobjanschi of Google presented a talk that outlined the following three patterns for using content providers to integrate RESTful web services into Android applications...

In this chapter, we’ll explore the second pattern in detail with our second Finch video example; this strategy will yield a number of important benefits for your applications. Due to the elegance with which this approach integrates network operations into Android MVC, we’ve given it the moniker “Network MVC.”

A future edition of Programming Android may address the other two approaches, as well as document more details of this Google presentation. After you finish reading this chapter, we suggest that you view Google’s 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.

何以心动 2024-10-23 15:34:56

Virgil Doobjanschi 的“开发 Android REST 客户端应用程序”引起了很多讨论,因为在会议期间或之后都没有提供源代码。

  • http://datadroid.foxykeep.com 下提供了参考实现(Google IO 会话在 / 下提到)推介会)。它是一个可以在您自己的应用程序中使用的库。
  • Android Priority Job Queue 的灵感来自 Doobjanschi 的演讲,对我来说听起来很有希望。

如果您知道更多实现,请评论。

"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.

  • A reference implementation is available under http://datadroid.foxykeep.com (the Google IO session is mentioned under /presentation). It is a library which you can use in your own application.
  • Android Priority Job Queue was inspired by Dobjanschi's talk and sounds very promising to me.

Please comment if you know more implementations.

谈场末日恋爱 2024-10-23 15:34:56

我们开发了一个解决此问题的库:RoboSpice

该库使用 Virgil Doobjanschi尼尔·古德曼,但是我们提供完整的一体化解决方案:

  • 异步执行(在后台 AndroidService 中)网络
    将返回 POJO 的请求(例如:REST 请求)
  • 缓存结果(以 Json、Xml、纯文本文件或二进制文件形式)
  • 通知您的活动(或任何其他上下文)网络结果
    请求他们是否还活着
  • 不会通知您的活动
    如果他们不再活着,结果
  • 会通知您的活动
    他们的 UI 线程
  • 使用简单但强大的异常处理模型,
  • 支持多个 ContentService 来聚合不同的 Web 服务
    结果
  • 支持请求执行的多线程
  • 强烈
    输入!
  • 是开源的;)
  • 并经过测试

我们实际上正在寻找社区的反馈。

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 :

  • executes asynchronously (in a background AndroidService) network
    requests that will return POJOs (ex: REST requests)
  • caches results (in Json, or Xml, or flat text files, or binary files)
  • notifies your activities (or any other context) of the result of the network
    request if they are still alive
  • doesn't notify your activities of the
    result if they are not alive anymore
  • notifies your activities on
    their UI Thread
  • uses a simple but robust exception handling model
  • supports multiple ContentServices to aggregate different web services
    results
  • supports multi-threading of request executions
  • is strongly
    typed !
  • is open source ;)
  • and tested

We are actually looking for feedback from the community.

Oo萌小芽oO 2024-10-23 15:34:56

Retrofit 在这里可能非常有帮助,它通过非常简单的配置为您构建一个适配器,例如:

Retrofit 将您的 REST API 转换为 Java 接口。

public interface GitHubService {
  @GET("/users/{user}/repos")
  List<Repo> listRepos(@Path("user") String user);
}

RestAdapter 类生成 GitHubService 接口的实现。

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .build();

GitHubService服务=restAdapter.create(GitHubService.class);
对生成的 GitHubService 的每次调用都会向远程 Web 服务器发出 HTTP 请求。

List<Repo> repos = service.listRepos("octocat");

欲了解更多信息,请访问官方网站: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.

public interface GitHubService {
  @GET("/users/{user}/repos")
  List<Repo> listRepos(@Path("user") String user);
}

The RestAdapter class generates an implementation of the GitHubService interface.

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .build();

GitHubService service = restAdapter.create(GitHubService.class);
Each call on the generated GitHubService makes an HTTP request to the remote webserver.

List<Repo> repos = service.listRepos("octocat");

for more information visit the official site: http://square.github.io/retrofit/

Note: the adapter RestAdapter you get from Retrofit is not derived from BaseAdapter you should make a wrapper for it somehow like this SO question
Why is my ListView empty after calling setListAdapter inside ListFragment?

烙印 2024-10-23 15:34:56

这有点晚了,但这里有一篇文章解释了演讲中的第一个模式:

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.

红ご颜醉 2024-10-23 15:34:56

对于初学者,您应该查看 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.

梦过后 2024-10-23 15:34:56

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文