Biblioteca de cliente REST API para Android


Estamos construyendo una aplicación de mensajería basada en la ubicación que utiliza Parse.com como back-end (Parse.com es similar a Urban Airship / PubNub, etc.) y ahora queremos cambiar a nuestro propio back-end para un mejor control. Para esto, hemos construido un nodo.back-end basado en js con funcionalidad expuesta sobre REST API

Para consumir esta API, queremos construir una biblioteca de Android (similar a Parse.com Android SDK) que abstrae todas las solicitudes HTTP / Respuesta o llamadas a la API REST y proporciona funciones para varias operaciones como getUsers(), SendMessage(), etc

Formas de implementar el cliente API REST en Android:

Ahora, teniendo en cuenta que queremos construir una biblioteca de Android y podría haber llamadas simultáneas a la API REST mientras el usuario interactúa con la aplicación, que enfoque sería el mejor para seguir adelante con ? Estoy abierto a otras sugerencias / recomendaciones también.

UPDATE : Primero construimos nuestra propia biblioteca usando IntentService + ResultReceiver que funcionó bien. Pero más tarde nos topamos con Android Async Http . Úsalo. ¡Es increíble!

Author: Madhur, 2012-11-19

6 answers

La mejor implimentación que he visto basada en Google IO Pro Tips 2010 es la biblioteca RoboSpice, que está basada en REST y funciona muy inteligentemente con el ciclo de vida de la actividad para no perder memoria.

Quick infografía la biblioteca está aquí

  • Los cargadores están diseñados para bases de datos, no para REST, se restablecen al restablecer la actividad, lo que significa que pierde sus datos.
  • Tarea asincrónica, simplemente no.
  • Intent Service + Result receiver es básicamente como RoboSpice trabajo, así que si usted está construyendo su propia lib, me gustaría tomar este enfoque!
  • El servicio también es bueno, similar al método IntentService, pero IntentService funciona un poco mejor en este caso.

El método Service quizás mejor, mira el servicio robospice usan un ExecutorService que termina el Service cuando se ha quedado sin Requests para funcionar, esto es más concurrencia de Java que específica de Android. Lo principal a tener en cuenta es que el servicio se ejecuta mientras se procesa las solicitudes entonces termina su auto si no quedan ninguno.

La ventaja de usar ExecutorService o cualquier tipo de grupo de subprocesos, es que puede definir cuántas solicitudes puede ejecutar a la vez. a menos que tenga una conexión muy rápida 2-4 es lo más que sugeriría.

 43
Author: Chris.Jenkins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-16 17:00:20

PUEDE SER QUE ESTA CLASE PUEDA AYUDAR :-

/*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 EJEMPLO SENCILLO PARA USAR ESTA CLASE:

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
Author: Bhavit S. Sengar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-09 10:14:13

He usado Retrofit y es realmente una buena biblioteca que proporciona una estructura fácil para administrar puntos finales y analizar datos/colecciones/objetos.

La documentación es lo suficientemente completa como para escribir código fácilmente.

CQFD > adelante

 7
Author: Hugo Gresse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-25 08:19:07

También puedes usar RESTDroid. Es bastante similar a RoboSpice pero más simple de usar (aunque también menos potente.)

Si crea un Parse.com módulo para RESTDroid, no dude en añadirlo en GitHub!

 4
Author: Pcriulan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-16 16:08:17

Si puedo agregar una cosa más, recientemente empecé a escribir una bonita biblioteca para implementar Motores (como los utilizados por MKNetworkKit en iOS) y Comandos para comunicarse con las API REST para Android. Podría ser útil para cualquiera que intente llegar a las API REST. https://github.com/m2d2/MDBaseAndroidLibraries

 1
Author: dineth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-04 03:06:16

También puedes probar Anotaciones de Android con el complemento rest-spring para realizar estas tareas automáticamente.

Usan un wrapper en spring framework para android y proporcionan una muy buena manera de manejar api rest.

Ejemplos:

Reemplazar AsyncTask - > doInBackground () con @ Background anotación:

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

Reemplazar runOnUiThread, onPostExecute () con @UIThread

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

Para API REST

crear cliente rest:

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

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

usar cliente rest:

@RestClient
MyRestClient myRestClient;

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

}
 1
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-07 04:54:24