Java
Request
Now that the Java application has an authorization code
, it can exchange it for an access_token
required to make a request to a vehicle.
1. Obtain an access token
In the previous section, we retrieved an authorization code
. The Java application must exchange the code
for an access_token
to make a request.
The access_token represents your application’s access to a vehicle on behalf of the vehicle owner.
After receiving the access_token
, the user can be redirected to the /vehicle
route which we will implement in the next step.
// src/main/java/Main.java
// global variable to save our accessToken
private static String access;
public static void main(String[] args) {
get("/exchange", (req, res) -> {
String code = req.queryMap("code").value();
// TODO: Request Step 1: Obtain an access token
Auth auth = client.exchangeCode(code);
// in a production app you'll want to store this in some kind of persistent storage
access = auth.getAccessToken();
return "";
})
}
2. Get vehicle attributes
Once the application has the access_token
, it can send requests to a vehicle using Smartcar’s API.
Once we have the vehicle attributes, we'll serialize them as JSON to return to the client.
get("/vehicle", (req, res) -> {
// TODO: Request Step 2: Get vehicle information
VehicleIds vehiclesResponse = Smartcar.getVehicles(access);
// the list of vehicle ids
String[] vehicleIds = vehiclesResponse.getVehicleIds();
// instantiate the first vehicle in the vehicle id list
Vehicle vehicle = new Vehicle(vehicleIds[0], access);
// Make a request to Smartcar API
VehicleAttributes attributes = vehicle.attributes();
System.out.println(gson.toJson(attributes));
// {
// "id": "36ab27d0-fd9d-4455-823a-ce30af709ffc",
// "make": "TESLA",
// "model": "Model S",
// "year": 2014
// }
res.type("application/json");
return gson.toJson(attributes);
}
Try it out
Make sure the server is running -
./gradlew run
Now you can go to localhost:8000/login
to see your Java app running!