DEV Community

Aashutosh Poudel
Aashutosh Poudel

Posted on

3 2

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay