GSON 的简单 POST 请求
示例 JSON:
{ 
    "id": "12345",
    "type": "android"
}
定义你的请求:
public class GetDeviceRequest {
    @SerializedName("deviceId")
    private String mDeviceId;
    public GetDeviceRequest(String deviceId) {
        this.mDeviceId = deviceId;
    }
    public String getDeviceId() {
        return mDeviceId;
    }
}
定义你的服务(要点击的端点):
public interface Service {
    @POST("device")
    Call<Device> getDevice(@Body GetDeviceRequest getDeviceRequest);
}
定义网络客户端的单例实例:
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;
    }
} 
为设备定义一个简单的模型对象:
public class Device {
    @SerializedName("id")
    private String mId;
    @SerializedName("type")
    private String mType;
    public String getId() {
        return mId;
    }
    public String getType() {
        return mType;
    }
}
定义控制器以处理对设备的请求
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 
            } 
        });