Languages
[Edit]
EN

Java - how to make Jsoup http POST request with json body payload and get json as response?

7 points
Created by:
Kate_C
2854

To make Jsoup HTTP Post with Json request and Json response,
the most important part of the code is to add the correct http headers:

Connection.Response execute = Jsoup.connect(url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json")

Jsoup full request can looks like this:

String jsonBody = "{\"userId\":12345,\"userHash\":\"abc123\"}";

String url = "http://localhost:8080/getUser";

Connection.Response execute = Jsoup.connect(url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json")
        .followRedirects(true)
        .ignoreHttpErrors(true)
        .ignoreContentType(true)
        .userAgent("Mozilla/5.0 AppleWebKit/537.36 (KHTML," +
                " like Gecko) Chrome/45.0.2454.4 Safari/537.36")
        .method(Connection.Method.POST)
        .requestBody(jsonBody)
        .maxBodySize(1_000_000 * 30) // 30 mb ~
        .timeout(0) // infinite timeout
        .execute();

Full working example with spring boot controller:

  • Jsoup main class with request and response
  • Spring boot controller
  • User request class
  • User response class

Jsoup main class with request and response:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

public class JsoupHttpPostWithJsonRequestAndJsonResponseExample {

    public static void main(String[] args) throws Exception {

        UserRequest userRequest = new UserRequest(12345L, "abc123");
        System.out.println("# UserRequest:");
        System.out.println(userRequest);

        String jsonBody = new ObjectMapper().writeValueAsString(userRequest);
        // String jsonBody = "{\"userId\":12345,\"userHash\":\"abc123\"}";
        System.out.println("# Json Body:");
        System.out.println(jsonBody);

        String url = "http://localhost:8080/getUser";
        Connection.Response execute = Jsoup.connect(url)
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .followRedirects(true)
                .ignoreHttpErrors(true)
                .ignoreContentType(true)
                .userAgent("Mozilla/5.0 AppleWebKit/537.36 (KHTML," +
                        " like Gecko) Chrome/45.0.2454.4 Safari/537.36")
                .method(Connection.Method.POST)
                .requestBody(jsonBody)
                .maxBodySize(1_000_000 * 30) // 30 mb ~
                .timeout(0) // infinite timeout
                .execute();

        int statusCode = execute.statusCode();
        System.out.println("statusCode: " + statusCode); //  200

        String responseJson = execute.body();
        ObjectMapper mapper = new ObjectMapper();
        UserResponse userResponse = mapper
                .readValue(responseJson, UserResponse.class);

        System.out.println("# UserResponse de-serialized:");
        System.out.println(userResponse);
    }
}

Output:

# UserRequest:
UserRequest{userId=12345, userHash='abc123'}
# Json Body:
{"userId":12345,"userHash":"abc123"}
statusCode: 200

# From spring boot controller - User request:
UserRequest(userId=12345, userHash=abc123)

# UserResponse de-serialized:
UserResponse{username='Seth', userAge=25}

Spring boot controller:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @PostMapping(path = "/getUser",
            consumes = "application/json", produces = "application/json")
    public UserResponse getUser(@RequestBody UserRequest userRequest) {
        System.out.println("# From spring boot controller - User request:");
        System.out.println(userRequest.toString());

        return new UserResponse("Seth", 25);
    }
}

User request class:

public class UserRequest {
    private long userId;
    private String userHash;

    public UserRequest() {

    }

    public UserRequest(long userId, String userHash) {
        this.userId = userId;
        this.userHash = userHash;
    }

    public long getUserId() {
        return userId;
    }

    public void setUserId(long userId) {
        this.userId = userId;
    }

    public String getUserHash() {
        return userHash;
    }

    public void setUserHash(String userHash) {
        this.userHash = userHash;
    }

    @Override
    public String toString() {
        return "UserRequest{" +
                "userId=" + userId +
                ", userHash='" + userHash + '\'' +
                '}';
    }
}

User response class:

public class UserResponse {
    private String username;
    private int userAge;

    public UserResponse() {

    }

    public UserResponse(String username, int userAge) {
        this.username = username;
        this.userAge = userAge;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getUserAge() {
        return userAge;
    }

    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }

    @Override
    public String toString() {
        return "UserResponse{" +
                "username='" + username + '\'' +
                ", userAge=" + userAge +
                '}';
    }
}

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.