我有一个REST服务,想要用Android来使用它。该服务(JAX-RS)发布JSON数据。所以主要的问题是:
谢谢
答案 0 :(得分:3)
从API级别8开始,您可以使用AndroidHTTPClient
,或者对于早期的API,您可以毫无问题地使用DefaultHttpClient
,并使用HttpPost
或HttpGet
发送数据。对于JSON
中的数据编码,是GSON
是一种很好的方法,但我认为org.json
会更容易使用。
答案 1 :(得分:2)
Spring Android有一个非常容易使用的RestTemplate。
http://static.springsource.org/spring-android/docs/1.0.x/reference/html/rest-template.html
例如:
String url = "http://mypretendservice.com/events";
RestTemplate restTemplate = new RestTemplate();
Event[] events = restTemplate.getForObject(url, Event[].class);
答案 2 :(得分:2)
Resteasy-mobile是一个完美的解决方案(https://github.com/tdiesler/resteasy-mobile)
它基本上是完全成熟的resteasy(有客户端框架)但是使用Apache HTTP Client而不是HttpURLConnection(在android上不存在)
以下是有关使用的更多信息(http://docs.jboss.org/resteasy/docs/2.3.1.GA//userguide/html_single/index.html#RESTEasy_Client_Framework)
这是为了maven
<dependency>
<groupId>org.jboss.resteasy.mobile</groupId>
<artifactId>resteasy-mobile</artifactId>
<version>1.0.0</version>
</dependency>
android端的一些示例代码
public class RestServices {
static RegisterSVC registerSVC;
static PushSVC pushSVC;
static TrackerSVC trackerSVC;
RestServices() {
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
}
public static RegisterSVC getRegisterSVC() {
return ProxyFactory.create(RegisterSVC.class,"http://143.248.194.236:8080/notification");
}
public static PushSVC getPushSVC() {
return ProxyFactory.create(PushSVC.class,"http://143.248.194.236:8080/notification");
}
public static TrackerSVC getTrackerSVC() {
return ProxyFactory.create(TrackerSVC.class,"http://143.248.194.236:8080/notification");
}
}
Android和服务器端的JAX-RS服务定义(PushSVC.java)
@Path("/mobile")
public interface PushSVC {
/*
Sample
curl --data '{"collapseKey":"asdf","contentList":{"aaaa":"you","ssss":"you2"}}' -X POST -H 'Content-type:application/json' -v http://localhost:8080/notification/mobile/11111/send
*/
@POST
@Path("/{uuid}/send")
@Consumes(MediaType.APPLICATION_JSON)
String sendPush( MessageVO message, @PathParam("uuid") String uuid);
}
模型MessageVO定义
public class MessageVO {
String collapseKey;
HashMap<String, String> contentList;
public MessageVO() {
}
public MessageVO(String collapseKey) {
this.collapseKey = collapseKey;
contentList = new HashMap<String, String>();
}
public void put(String key, String value)
{
this.contentList.put(key,value);
}
public String getCollapseKey() {
return collapseKey;
}
public HashMap<String, String> getContentList() {
return contentList;
}
}
这是android
上的方法调用public class Broadcast extends AsyncTask<Context,Void,Void>
{
@Override
protected Void doInBackground(Context... contexts) {
MessageVO message = new MessageVO("0");
message.put("tickerText","Ticker ne` :D");
message.put("contentTitle","Title ne` :D");
message.put("contentText","Content ne` :D");
RestServices.getPushSVC().sendPush(message,TrackInstallation.id(contexts[0]).toString());
return null;
}
}
这很简单,所有编写的代码都是可重用的,样板代码几乎不存在
希望这对每个人都有所帮助。