2016-12-30 61 views
1

我正在開發使用API​​爲HyperTrack的API應用程序(它是一種提供API以實時跟蹤移動設備的Web服務,它還提供了在不同API中的任務和驅動程序處理功能。)如何參照API的shell命令向API發出POST請求?

Start a Trip功能,需要使用我下面的shell命令來獲得驅動程序項:

Driver API: 
curl -H "Authorization: token YOUR_SK_TOKEN" \ 
-H "Content-Type: application/json" \ 
-X POST \ 
-d "{\"name\": \"Test driver\", \"vehicle_type\": \"car\"}" \ 
https://app.hypertrack.io/api/v1/drivers/ 

這是我如何實現使用Retrofit2這兩個API具有以下請求接口:

public interface DriverRequestInterface 
{ 
    @Headers ({ 
     "Authorization: token SECRET_KEY", 
     "Content-Type: application/json" 
    }) 
    @POST ("api/v1/drivers") 
    Call<DriverJSONResponse> getJSON (@Body DriverJSONResponse jsonResponse); 
} 

這裏是我DriverJSONResponse:

public class DriverJSONResponse 
{ 
    /* 
    JSON Object Fields 
    @SerializedName ("count") private int count; 
    */ 

    @SerializedName ("name") private String name; 
    @SerializedName ("vehicle_type") private String vehicleType; 

    public DriverJSONResponse(String name, String vehicleType) 
    { 
     this.name = name; 
     this.vehicleType = vehicleType; 
    } 

    /* 
    Setter and Getter of JSON Object Fields 
    public void setCount (int count) { this.count = count; } 
    public int getCount() { return count; } 
    */ 
} 

因此,與這個地步,我收到一個GET響應,無法發佈。我收到帶有結果列表的JSON對象,但無法將任何內容發佈到API。

如何通過參考API的shell命令向API發出POST請求?

回答

3

由於DriverJSONResponse類包含與namevehicle_type沿等領域,上面的代碼通行證以下數據到POST

{"count":0, "name":"Brian", "vehicle_type":"car", "results":[] } 

這導致JSON解析錯誤。

因此,使用另一個模型類,將POST參數,如:

public class DriverJSON 
{ 
    @SerializedName ("name") private String name; 
    @SerializedName ("vehicle_type") private String vehicleType; 

    public DriverJSON(String name, String vehicleType) 
    { 
     this.name = name; 
     this.vehicleType = vehicleType; 
    } 

    public String getName() { return name; } 
    public String getVehicleType() { return vehicleType; } 
} 

,並通過這個模型類的RequestInterface,如:

public interface DriverRequestInterface 
{ 
    @Headers ({ 
     "Authorization: token YOUR_SECRET_KEY", 
     "Content-Type: application/json" 
    }) 
    @POST ("api/v1/drivers/") 
    Call<DriverJSONResponse> getJSON (@Body DriverJSON json); 
} 

而且不要忘了你的模型DriverJSONResponse根據您期望收到的JSON對象。