DEV Community

Aashutosh Poudel
Aashutosh Poudel

Posted on

Creating basic GET and POST requests in OkHttp and Java

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();
}

Enter fullscreen mode Exit fullscreen mode

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();

}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)