gpt4 book ai didi

android - 如何引用API的shell命令向API发起POST请求?

转载 作者:行者123 更新时间:2023-11-29 17:07:48 26 4
gpt4 key购买 nike

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

Start a Trip需要我使用以下 shell 命令获取驱动程序 key 的功能:

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/

这就是我使用带有以下请求接口(interface)的 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 响应,而不是 POST。我收到带有结果列表的 JSON 对象,但无法向 API 发布任何内容。

如何引用API的shell命令向API发起POST请求?

最佳答案

由于 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 进行建模。

关于android - 如何引用API的shell命令向API发起POST请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41392312/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com