A simple way of making POST request in OkHttp and Java:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import okhttp3.*;
LoginUser user = new LoginUser(username, password);
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String postBody = ow.writeValueAsString(user);
Request request =
new Request.Builder()
.url(API_URL + "/Account/login")
.post(RequestBody.create(postBody.trim(), JSON))
.build();
String accessToken = null;
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful() || response.code() != 200)
log.warn("Couldn't access the API");
User loggedInUser =
new ObjectMapper()
.readValue(response.body().string(), User.class);
accessToken = loggedInUser.getAccessToken();
}
Next, a simple way of making GET request in OkHttp and Java:
Request request1 = new Request.Builder()
.url(API_URL + "/Allcustomers")
.header("Authorization", "Bearer " + accessToken)
.build();
try (Response response = client.newCall(request1).execute()) {
if (!response.isSuccessful() || response.code() != 200)
log.warn("Couldn't access the list of users");
AllCustomers allCustomers =
new ObjectMapper()
.readValue(response.body().string(), AllCustomers.class);
List<Customer> customerList = allCustomers.getResponseData();
}
Top comments (0)