Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android REST客户端,示例?_Java_Android_Rest_Restapi - Fatal编程技术网

Java Android REST客户端,示例?

Java Android REST客户端,示例?,java,android,rest,restapi,Java,Android,Rest,Restapi,即使此线程已接受答案,也可以自由提出其他想法,您可以使用或喜欢 我见过这些文章: 这让我看到了关于REST客户端应用程序的Google I/O 2010视频 从现在起,我一直在我的应用程序控制器类中创建REST组件作为静态组件 从现在开始,我想,我应该改变这种模式。指出该应用程序是如何在Android上编写REST客户端的绝佳示例。被告知这种方法过于复杂 那么,有人能告诉我们什么是最佳实践吗?简而言之。 IOSched应用程序对于示例用例来说太复杂了。维吉尔·多布扬斯基(Virg

即使此线程已接受答案,也可以自由提出其他想法,您可以使用或喜欢


我见过这些文章:

这让我看到了关于REST客户端应用程序的Google I/O 2010视频

从现在起,我一直在我的应用程序控制器类中创建REST组件作为静态组件

从现在开始,我想,我应该改变这种模式。指出该应用程序是如何在Android上编写REST客户端的绝佳示例。被告知这种方法过于复杂

那么,有人能告诉我们什么是最佳实践吗?简而言之。
IOSched应用程序对于示例用例来说太复杂了。

维吉尔·多布扬斯基(Virgil Dobjanschi)的“开发Android REST客户端应用程序”引发了很多讨论,因为在会话期间或之后没有提供源代码

我所知道的唯一参考实现(如果您了解更多,请发表评论)位于(Google IO会话在/presentation中提到)。它是一个可以在您自己的应用程序中使用的库

第二个链接要求使用“最佳”REST框架,这在stackoverflow中有大量讨论。对我来说,应用程序的大小很重要,其次是实现的性能

  • 通常我使用纯org.json implemantation,它是Android的一部分,因为API级别为1,因此不会增加应用程序的大小
  • 对我来说,非常有趣的是在评论中找到的信息:从Android 3.0 Honeycom开始,GSON的流式解析器包含在Android.util.JsonReader中。不幸的是,这些评论已经没有了
  • springandroid(我有时使用)支持Jackson和GSON。这些都指向一个问题
因此,对于complexer场景,我坚持使用org.json或GSON。对于org.json实现的体系结构,我使用一个表示服务器用例的静态类(例如findPerson、getPerson)。我从服务调用此功能,并使用正在进行映射(特定于项目)和网络IO(我自己的REST模板,用于普通GET或POST)的实用程序类。我尽量避免使用反射。

EDIT 2(2017年10月): 现在是2017年。只要使用改装。几乎没有理由使用其他任何东西

编辑: 在本次编辑时,原始答案已经有一年半的历史了。尽管原始答案中提出的概念仍然适用,正如其他答案所指出的,现在有一些库可以让您更轻松地完成这项任务。更重要的是,其中一些库为您处理设备配置更改

以下保留原始答案以供参考。但也请花时间检查一些Android的Rest客户端库,看看它们是否适合您的用例。下面是我评估过的一些库的列表。这绝不是一份详尽无遗的清单

  • (来自谷歌)

原始答复: 介绍我在Android上使用REST客户端的方法。不过我并不认为这是最好的:)另外,请注意,这是我根据自己的要求提出的。如果您的用例需要,您可能需要有更多的层/增加更多的复杂性。例如,我根本没有本地存储;因为我的应用程序可以容忍一些REST响应的丢失

我的方法只是在封面下使用
AsyncTask
s。在我的例子中,我从我的
活动
实例中“调用”这些任务;但要完全考虑屏幕旋转等情况,您可以选择从
服务
或类似服务调用它们

我有意识地选择REST客户机本身作为API。这意味着,使用我的REST客户端的应用程序甚至不需要知道实际的REST URL和使用的数据格式

客户端将有两层:

  • 顶层:该层的目的是提供反映RESTAPI功能的方法。例如,您可以有一个Java方法对应于RESTAPI中的每个URL(甚至两个——一个用于GET,一个用于POST)。
    这是REST客户端API的入口点。这是应用程序通常使用的层。它可以是单身,但不一定是单身。
    REST调用的响应由该层解析为POJO并返回给应用程序

  • 这是较低级别的
    AsyncTask
    层,它使用HTTP客户机方法实际执行并进行REST调用

  • 此外,我选择使用回调机制将
    AsyncTask
    s的结果传回应用程序

    足够的文本。现在让我们看一些代码。让我们假设一个REST API URL-

    顶层可能如下所示:

       /**
     * Entry point into the API.
     */
    public class HypotheticalApi{   
        public static HypotheticalApi getInstance(){
            //Choose an appropriate creation strategy.
        }
        
        /**
         * Request a User Profile from the REST server.
         * @param userName The user name for which the profile is to be requested.
         * @param callback Callback to execute when the profile is available.
         */
        public void getUserProfile(String userName, final GetResponseCallback callback){
            String restUrl = Utils.constructRestUrlForProfile(userName);
            new GetTask(restUrl, new RestTaskCallback (){
                @Override
                public void onTaskComplete(String response){
                    Profile profile = Utils.parseResponseAsProfile(response);
                    callback.onDataReceived(profile);
                }
            }).execute();
        }
        
        /**
         * Submit a user profile to the server.
         * @param profile The profile to submit
         * @param callback The callback to execute when submission status is available.
         */
        public void postUserProfile(Profile profile, final PostCallback callback){
            String restUrl = Utils.constructRestUrlForProfile(profile);
            String requestBody = Utils.serializeProfileAsString(profile);
            new PostTask(restUrl, requestBody, new RestTaskCallback(){
                public void onTaskComplete(String response){
                    callback.onPostSuccess();
                }
            }).execute();
        }
    }
    
    
    /**
     * Class definition for a callback to be invoked when the response data for the
     * GET call is available.
     */
    public abstract class GetResponseCallback{
        
        /**
         * Called when the response data for the REST call is ready. <br/>
         * This method is guaranteed to execute on the UI thread.
         * 
         * @param profile The {@code Profile} that was received from the server.
         */
        abstract void onDataReceived(Profile profile);
        
        /*
         * Additional methods like onPreGet() or onFailure() can be added with default implementations.
         * This is why this has been made and abstract class rather than Interface.
         */
    }
    
    /**
     * 
     * Class definition for a callback to be invoked when the response for the data 
     * submission is available.
     * 
     */
    public abstract class PostCallback{
        /**
         * Called when a POST success response is received. <br/>
         * This method is guaranteed to execute on the UI thread.
         */
        public abstract void onPostSuccess();
    
    }
    
    /**
     * An AsyncTask implementation for performing GETs on the Hypothetical REST APIs.
     */
    public class GetTask extends AsyncTask<String, String, String>{
        
        private String mRestUrl;
        private RestTaskCallback mCallback;
        
        /**
         * Creates a new instance of GetTask with the specified URL and callback.
         * 
         * @param restUrl The URL for the REST API.
         * @param callback The callback to be invoked when the HTTP request
         *            completes.
         * 
         */
        public GetTask(String restUrl, RestTaskCallback callback){
            this.mRestUrl = restUrl;
            this.mCallback = callback;
        }
        
        @Override
        protected String doInBackground(String... params) {
            String response = null;
            //Use HTTP Client APIs to make the call.
            //Return the HTTP Response body here.
            return response;
        }
        
        @Override
        protected void onPostExecute(String result) {
            mCallback.onTaskComplete(result);
            super.onPostExecute(result);
        }
    }
    
        /**
         * An AsyncTask implementation for performing POSTs on the Hypothetical REST APIs.
         */
        public class PostTask extends AsyncTask<String, String, String>{
            private String mRestUrl;
            private RestTaskCallback mCallback;
            private String mRequestBody;
            
            /**
             * Creates a new instance of PostTask with the specified URL, callback, and
             * request body.
             * 
             * @param restUrl The URL for the REST API.
             * @param callback The callback to be invoked when the HTTP request
             *            completes.
             * @param requestBody The body of the POST request.
             * 
             */
            public PostTask(String restUrl, String requestBody, RestTaskCallback callback){
                this.mRestUrl = restUrl;
                this.mRequestBody = requestBody;
                this.mCallback = callback;
            }
            
            @Override
            protected String doInBackground(String... arg0) {
                //Use HTTP client API's to do the POST
                //Return response.
            }
            
            @Override
            protected void onPostExecute(String result) {
                mCallback.onTaskComplete(result);
                super.onPostExecute(result);
            }
        }
        
        /**
         * Class definition for a callback to be invoked when the HTTP request
         * representing the REST API Call completes.
         */
        public abstract class RestTaskCallback{
            /**
             * Called when the HTTP request completes.
             * 
             * @param result The result of the HTTP request.
             */
            public abstract void onTaskComplete(String result);
        }
    
    以下是应用程序如何使用API(在
    活动
    服务
    中):


    我希望这些评论足以解释设计;但我很乐意提供更多信息。

    切勿使用AsynTask执行网络请求或任何需要持久化的操作。异步任务与您的活动密切相关,如果用户在重新创建应用程序后更改屏幕方向,则异步任务将停止


    我建议您将服务模式与Intent Service和ResultReceiver结合使用。看一看。它是一个库,允许您异步执行任何类型的REST请求,并通过实现Virgil Dobjanschi服务模式的请求侦听器通知您的UI。

    还有一个库具有更干净的API和类型安全数据。

    下面是一个简单的用法示例

    Http http = HttpFactory.create(context);
    http.post("http://example.com/users")
        .data(new User("John"))
        .execute();
    
    或者更复杂的回调

    Http http = HttpFactory.create(context);
    http.post("http://example.com/users")
        .data(new User("John"))
        .handler(new ResponseHandler<Void>() {
            @Override
            public void success(Void ignore, HttpResponse response) {
            }
    
            @Override
            public void error(String message, HttpResponse response) {
            }
    
            @Override
            public void failure(NetworkError error) {
            }
    
            @Override
            public void complete() {
            }
        }).execute();
    
    Http=HttpFactory.create(上下文); http.post(“http://example.com/users") .数据(新用户(“John”)) .handler(新的ResponseHandler(){ @凌驾 公共作废成功(作废忽略,Http
    Http http = HttpFactory.create(context);
    http.post("http://example.com/users")
        .data(new User("John"))
        .handler(new ResponseHandler<Void>() {
            @Override
            public void success(Void ignore, HttpResponse response) {
            }
    
            @Override
            public void error(String message, HttpResponse response) {
            }
    
            @Override
            public void failure(NetworkError error) {
            }
    
            @Override
            public void complete() {
            }
        }).execute();