我们正在构建一个基于位置的消息传递应用,它使用Parse.com作为后端 (Parse.com类似于Urban Airship / PubNub等)我们现在想切换到我们自己的后端以获得更好的控制。为此,我们构建了一个基于node.js的后端,其功能通过REST API公开
要使用此API,我们希望构建一个Android库(类似于Parse.com's Android SDK),它抽象所有HTTP请求/响应或REST API调用,并为各种操作提供直接函数,如getUsers(),sendMessage( )等等
在Android中实施REST API客户端的方法:
现在,考虑到我们想构建一个android库,并且在用户与应用程序交互时可能会同时进行REST API调用,哪种方法最好继续进行?我也对其他建议/建议持开放态度。
UPDATE :我们首先使用IntentService + ResultReceiver构建了我们自己的库,该工作正常。但我们后来偶然发现了Android Async Http。用它。太棒了!
答案 0 :(得分:43)
我见过的基于Google IO Pro Tips 2010的最佳实践是RoboSpice库,它基于REST,非常巧妙地与Activity生命周期一起工作,以避免内存泄漏。
快速infographic图书馆为here
Service
方法可能更好,look at the robospice service他们使用ExecutorService
,当Service
耗尽Requests
时,ExecutorService
会终止, Java特定于Java并发性。需要注意的是,服务在处理请求时运行,然后如果没有剩下就终止自己。
使用{{1}}或任何类型的线程池的优点是,您可以定义一次可以运行的请求数。除非你有一个非常快的连接2-4是我所建议的最多。
答案 1 :(得分:8)
可以帮助这个课程: -
/*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;
}
}
使用此类的简单示例:
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();
}
答案 2 :(得分:7)
答案 3 :(得分:4)
您也可以使用RESTDroid。它与RoboSpice非常相似,但使用起来更简单(虽然也不那么强大。)
如果您为RESTDroid创建Parse.com模块,请不要犹豫,将它添加到GitHub上!
答案 4 :(得分:1)
如果我可以添加一件事,我最近开始编写一个很好的库来实现Engines(在iOS中由MKNetworkKit使用)和Commands与Android的REST API进行通信。可能对尝试访问REST API的任何人都有帮助。 https://github.com/m2d2/MDBaseAndroidLibraries
答案 5 :(得分:1)
您还可以尝试使用 Android Annotations rest-spring 插件自动执行这些任务。
他们在 spring framework for android 上使用了一个包装器,并提供了一个非常好的方法来处理 rest apis 。
<强> 示例: 强>
替换AsyncTask - &gt;带有@Background注释的doInBackground():
@Background
protected void backgroundWork(){
// do something in background
}
用@UiThread替换runOnUiThread,onPostExecute()
@UiThread
protected void uiWork(){
// do something on UI Thread
}
适用于Rest API的
创建rest客户端:
@Rest(rootUrl = "http://company.com/ajax/services",
converters = { MappingJackson2HttpMessageConverter.class })
public interface MyRestClient {
@Get("/events")
EventList getEvents();
}
使用rest client:
@RestClient
MyRestClient myRestClient;
public void showAllEvents(){
EventList list = myRestClient.getEvents();
// do something with this list
}