EN
Java Jsoup - simple http GET example with json parsing to java DTO object
1
answers
2
points
How to make simple HTTP GET request with java JSOUP library?
1 answer
3
points
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