简体   繁体   中英

How do I communicate with a REST API using Java/Android?

Afternoon,

I am new to the forums so please go easy.

I am looking to code a java package within an android application that will GET, POST, UPDATE and DELETE to a Trading REST API. https://labs.ig.com/gettingstarted is this possible using the HttpClient library within Java. I haven't found much in the realm of tutorials, does Android have a library that I could use?

I appreciate any pointers.

Thanks in advance...

EDIT: Is this possible within the Java API's it seems like it should be standard functionality but can't find anything in the Java tutorial.

您可以尝试Spring RestTemplate for android ,对于REST来说已经足够了。

I'd look into either:

Retrofit http://square.github.io/retrofit/

public interface GitHubService {
  @GET("/users/{user}/repos")
  List<Repo> listRepos(@Path("user") String user);
}

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .build();

GitHubService service = restAdapter.create(GitHubService.class);

List<Repo> repos = service.listRepos("octocat");

Ion https://github.com/koush/ion

JsonObject json = new JsonObject();
json.addProperty("foo", "bar");

Ion.with(context)
.load("http://example.com/post")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
   @Override
    public void onCompleted(Exception e, JsonObject result) {
        // do stuff with the result or error
    }
});

Whichever you prefer. You can even mix Spring-Android or Retrofit with RoboSpice as per https://github.com/octo-online/RoboSpice-samples and it'll handle the background-thread stuff for you for the download.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM