REST API Client Library pour Android

nous sommes en train de construire une application de messagerie basée sur la localisation qui utilise Parse.com comme back-end (Parse.com est similaire à Urban Airship / PubNub, etc) et nous voulons maintenant passer à notre propre back-end pour un meilleur contrôle. Pour cela, nous avons construit un nœud.js en fonction de back-end avec des fonctionnalités exposées sur l'API REST

pour consommer cette API, nous voulons construire une bibliothèque Android (similaire àParse.com ' s Android SDK) qui supprime tous les appels HTTP Requests/Response ou REST API et fournit des fonctions directes pour diverses opérations comme getUsers (), sendMessage (), etc

façons d'implémenter REST API Client dans Android:

  • en utilisant IntentService + ResultReceiver
  • Service
  • AsyncTask
  • en utilisant Chargeurs

maintenant, considérant que nous voulons construire une bibliothèque android et qu'il pourrait y avoir des appels D'API REST simultanés pendant que l'utilisateur est interagir avec l'application, quelle approche serait la meilleure pour aller de l'avant ? Je suis ouvert à d'autres suggestions / recommandations.

UPDATE: nous avons d'abord construit notre propre bibliothèque en utilisant IntentService + ResultReceiver qui a bien fonctionné. Mais nous avons plus tard trébuché sur Android Async Http. Utiliser. C'est génial!

45
demandé sur Madhur 2012-11-19 00:11:39

6 réponses

la meilleure implémentation que j'ai vu sur la base de Google IO Pro Tips 2010 est la bibliothèque RoboSpice, qui est basée sur le repos et fonctionne très habilement avec le cycle de vie de L'activité pour ne pas perdre de mémoire.

Rapide infographie la bibliothèque est ici

  • les chargeurs sont conçus pour la base de données, pas pour le repos, ils sont réinitialisés sur la réinitialisation de l'activité ce qui signifie que vous perdez vos données.
  • tâche Async, juste Non.
  • Service D'Intention + Résultat le récepteur est essentiellement comment fonctionne RoboSpice, donc si vous construisez votre propre lib, je prendrais cette approche!
  • Service est également bon, semblable à la IntentService Méthode, mais IntentService fonctionne un peu mieux dans ce cas.

Service méthode peut-être mieux, voir la robospice service ils utilisent un ExecutorService qui termine le Service quand il est à court d' Requests pour travailler à travers, c'est plus la concurrence Java que Android spécifique. Chose principale à noter que le service fonctionne pendant le traitement des requêtes puis se termine si elles ne sont plus.

L'avantage de l'utilisation de l' ExecutorService ou n'importe quel type de pool de threads, est que vous pouvez définir combien de requêtes Vous pouvez exécuter à la fois. sauf si vous avez une connexion rapide 2-4 est la plus je n'aurais jamais penser.

43
répondu Chris.Jenkins 2013-12-16 17:00:20

MAY BE THIS CLASS CAN HELP : -

/*Copyright 2014 Bhavit Singh Sengar
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package com.infotech.zeus.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.widget.Toast;

public class RestClient {


        JSONObject data = new JSONObject();
        String url;
        String headerName;
        String headerValue;

        public RestClient(String s){

            url = s;
        }


        public void addHeader(String name, String value){

            headerName = name;
            headerValue = value;

        }

        public void addParam(String key, String value){

            try {
                data.put(key, value);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }

        public String executePost(){  // If you want to use post method to hit server

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader(headerName, headerValue);
            HttpResponse response = null;
            String result = null;
            try {
                StringEntity entity = new StringEntity(data.toString(), HTTP.UTF_8);
                httpPost.setEntity(entity);
                response = httpClient.execute(httpPost);
                HttpEntity entity1 = response.getEntity();
                result = EntityUtils.toString(entity1);
                return result;
                //Toast.makeText(MainPage.this, result, Toast.LENGTH_LONG).show();
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return result;



        }

        public String executeGet(){ //If you want to use get method to hit server

            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            String result = null;
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            try {
                result = httpClient.execute(httpget, responseHandler);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return result;
        }
}

UN EXEMPLE SIMPLE POUR UTILISER CETTE CLASSE:

RestClient client = new RestClient("http://www.example.com/demo.php");  //Write your url here
        client.addParam("Name", "Bhavit"); //Here I am adding key-value parameters
        client.addParam("Age", "23");

        client.addHeader("content-type", "application/json"); // Here I am specifying that the key-value pairs are sent in the JSON format

        try {
            String response = client.executePost(); // In case your server sends any response back, it will be saved in this response string.

        } catch (Exception e) {
            e.printStackTrace();
        }
7
répondu Bhavit S. Sengar 2014-04-09 10:14:13

j'ai utilisé Rénovation et c'est vraiment une bonne bibliothèque qui fournit une structure facile pour la gestion des paramètres et analyser les données/collections/objet.

la documentation est assez complète pour écrire facilement votre code.

CQFD > aller

7
répondu Hugo Gresse 2016-01-25 08:19:07

vous pouvez aussi utiliser RESTDroid. Il est assez similaire à RoboSpice mais plus simple à utiliser (bien que moins puissant.)

si vous créez un Parse.com module pour RESTDroid, n'hésitez pas à l'ajouter sur GitHub!

4
répondu Pcriulan 2013-07-16 16:08:17

si je peux ajouter une chose de plus, j'ai récemment commencé à écrire une belle bibliothèque pour implémenter des moteurs (comme utilisé par Mknetworkkkit dans iOS) et des commandes pour communiquer avec les API REST pour Android. Ça pourrait être utile à tous ceux qui essaient de joindre les APIs de repos. https://github.com/m2d2/MDBaseAndroidLibraries

1
répondu dineth 2013-02-04 03:06:16

Vous pouvez également essayer Annotations Androidreste-printemps plugin pour effectuer ces tâches automatiquement.

Ils utilisent un wrapper sur framework spring pour android et de fournir une très bonne façon de gérer api rest.

Exemples:

remplacer AsyncTask - > doInBackground () par @Background annotation:

@Background
protected void backgroundWork(){
    // do something in background
}

remplacer runOnUiThread, onPostExecute () par @UiThread

@UiThread
protected void uiWork(){
    // do something on UI Thread
}

Pour le Repos de l'API

créer un client rest:

@Rest(rootUrl = "http://company.com/ajax/services",
      converters = { MappingJackson2HttpMessageConverter.class })
public interface MyRestClient {

    @Get("/events")
    EventList getEvents();
}

utiliser le reste de client:

@RestClient
MyRestClient myRestClient;

public void showAllEvents(){
    EventList list = myRestClient.getEvents();
    // do something with this list

}
1
répondu 2016-05-07 04:54:24