Languages

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

2 points
Asked by:
AnnLen
1879

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

1 answers
3 points
Answered by:
AnnLen
1879

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join