Top community members

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

Java Jsoup - simple http GET example with json parsing to java DTO object

2 points
Asked by:
AnnLen
1666

How to make simple HTTP GET request with java JSOUP library?

1 answers
3 points
Answered by:
AnnLen
1666

To run this example we need to have some working REST API backend. This example was tested on my localhost tomcat, where I have some simple method which return user data.

Simple example:

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

public class JsoupTests {

    @Test
    public void test() throws Exception {

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

        Connection.Response response = Jsoup.connect(url)
                .followRedirects(true)
                .ignoreHttpErrors(true)
                .userAgent("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like " +
                        "Gecko) Chrome/45.0.2454.4 Safari/537.36")
                .method(Connection.Method.GET)
                .timeout(15000)
                .ignoreContentType(true)
                .execute();

        String responseJson = response.body();

        ObjectMapper mapper = new ObjectMapper();
        UserResponse resp = mapper.readValue(responseJson, UserResponse.class);

        // UserResponse{username='Seth', userAge=25}
        System.out.println(resp.toString());
    }
}

Output:

UserResponse{username='Seth', userAge=25}

 

0 comments Add comment

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more