Sample JSON:
{
"id": "12345",
"type": "android"
}
Define your request:
public class GetDeviceRequest {
@SerializedName("deviceId")
private String mDeviceId;
public GetDeviceRequest(String deviceId) {
this.mDeviceId = deviceId;
}
public String getDeviceId() {
return mDeviceId;
}
}
Define your service (endpoints to hit):
public interface Service {
@POST("device")
Call<Device> getDevice(@Body GetDeviceRequest getDeviceRequest);
}
Define your singleton instance of the network client:
public class RestClient {
private static Service REST_CLIENT;
static {
setupRestClient();
}
private static void setupRestClient() {
// Define gson
Gson gson = new Gson();
// Define our client
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://example.com/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
REST_CLIENT = retrofit.create(Service.class);
}
public static Retrofit getRestClient() {
return REST_CLIENT;
}
}
Define a simple model object for the device:
public class Device {
@SerializedName("id")
private String mId;
@SerializedName("type")
private String mType;
public String getId() {
return mId;
}
public String getType() {
return mType;
}
}
Define controller to handle the requests for the device
public class DeviceController {
// Other initialization code here...
public void getDeviceFromAPI() {
// Define our request and enqueue
Call<Device> call = RestClient.getRestClient().getDevice(new GetDeviceRequest("12345"));
// Go ahead and enqueue the request
call.enqueue(new Callback<Device>() {
@Override
public void onSuccess(Response<Device> deviceResponse) {
// Take care of your device here
if (deviceResponse.isSuccess()) {
// Handle success
//delegate.passDeviceObject();
}
}
@Override
public void onFailure(Throwable t) {
// Go ahead and handle the error here
}
});