如何参考API的Shell命令向API提出发布请求



我正在开发使用HyperTrack的API的Android应用程序(这是一种提供其API的Web服务,以实时跟踪移动设备。它还提供任务和任务功能驱动程序在单独的API中处理。)

有一个启动旅行功能,要求我使用shell命令在下面使用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);
}

这是我的驱动程序:

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; }
    */
}

到目前为止,我正在收到一个响应,而不是发布。我正在接收带有结果列表的JSON对象,但无法将任何内容发布到API。

如何参考API的shell命令?

由于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);
}

不要忘记根据您期望收到的JSON对象建模DriverJSONResponse

最新更新