I am developing Android Application that uses API of HyperTrack (It is a web service that provides it’s APIs for the purpose of tracking Mobile Devices in real-time. It also provides functionality of Task and Driver handling in separate APIs.)
There is Start a Trip Functionality that requires me to get Driver Key using shell command below:
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/
This is how I am implementing these two APIs using Retrofit2 with following Request Interface:
public interface DriverRequestInterface
{
@Headers ({
"Authorization: token SECRET_KEY",
"Content-Type: application/json"
})
@POST ( "api/v1/drivers" )
Call<DriverJSONResponse> getJSON (@Body DriverJSONResponse jsonResponse);
}
And Here is my 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; }
*/
}
So far with this, I am receiving a GET response, not POST. I am receiving JSON Object with list of Results but not able to post anything to API.
How can I make a POST request to the API with reference to the shell command of API?
Since the DriverJSONResponse
class contains other fields along with name
and vehicle_type
, the code above passes following data to the POST
:
{"count":0, "name":"Brian", "vehicle_type":"car", "results":[] }
which results in JSON Parsing Error.
So, use another model class for passing the POST
parameters, like:
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; }
}
and pass this model class in the RequestInterface
like:
public interface DriverRequestInterface
{
@Headers ({
"Authorization: token YOUR_SECRET_KEY",
"Content-Type: application/json"
})
@POST ( "api/v1/drivers/" )
Call<DriverJSONResponse> getJSON (@Body DriverJSON json);
}
And don't forget to model your DriverJSONResponse
in accordance with the JSON Object you expect to receive.