It would be nice if you help me to call a simple API GET method using Retrofit. I have added the Gson and Retrofit jar file to the build path.
Here is the interface
:
public interface MyInterface {
@GET("/my_api/shop_list")
Response getMyThing(@Query("mid") String param1);
}
I am getting results only (in log cat) if i call the following in AsyncTask else i am getting NetworkOrMainThreadException
How should i call this?
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://IP:Port/")
.setLogLevel(RestAdapter.LogLevel.FULL).build();
MyInterface service = restAdapter
.create(MyInterface.class);
mResponse = service.getMyThing("455744");
return null;
}
- Do i really have to call the Restadapter in AsyncTask?
- How can i get the JsonObject from the response?
Retrofit gives you the option of synchronous and asynchronous. Depending on how you declare your interface method, it will either be synchronous or asynchronous.
If you declare your API synchronously then you'll responsible of executing it in a
Thread
.Please read the "SYNCHRONOUS VS. ASYNCHRONOUS VS. OBSERVABLE" section on Retrofit's website. This will explain to you the basics on how to declare your APIs for your different needs.
The simplest way of getting access to your JSON class object is to map it to a Java object and let Retrofit do the conversion for you.
If for example the returned JSON for your rest api was
Then you could create a
Java
classes like soThen simply declare your api like so
And use it
Based on the JSON you've provided in the comments you would have do to something like this
This is kind of ugly but it's because of the JSON. My recommendation would be to simplify your JSON by removing the "response" inner object if you can, like so
Then your POJO could then become simpler like so