Http Rest Client
RestClient that parses:
Features
- Support for cookies
- Flexibility provided by plugins
Requirements
- Java 8 or newer
Maven artifact
<dependency>
<groupId>org.jsoftware</groupId>
<artifactId>rest-client</artifactId>
<version>1.5</version>
</dependency>
Examples:
Http GET request for JSON response:
RestClientFactory factory = new RestClientFactory();
try(RestClient restClient = factory.newRestClient()) {
restClient.setPlugins(Arrays.asList(new VerbosePlugin(false, System.out))); // add verbose plugin - it prints request and response to stdout
RestClientResponse response = restClient.get("https://api.stackexchange.com/2.2/answers") // API URL (http get)
.parameter("pagesize", 5) // Parameters
.parameter("order", "desc")
.parameter("sort", "activity")
.parameter("site", "stackoverflow")
.execute(); // execute http call
List<Number> questionIds = (List<Number>) response.json("$..answer_id"); // get all answer_id fields from response
}
More about syntax for .json(String) method argument can be found here.
Http GET request for XML response:
RestClientFactory factory = new RestClientFactory();
try(RestClient restClient = factory.newRestClient()) {
RestClientResponse response = restClient.get("https://api.somewhere.com.com/xml/call") // API URL (http get)
.execute();
NodeList nList = (NodeList) response.xPath("/answer/items/", XPathConstants.NODESET); // fetch xml data using XPath notation
}
Http POST request:
Emulate sending html form:
RestClientFactory factory = new RestClientFactory();
try(RestClient restClient = factory.newRestClient()) { // new instance of RestClient
RestClientResponse response = restClient.post("https://somewhere.com") // API URL (http post)
.parameter("username", "John") // Http form parameters
.parameter("password", "John's password")
.execute(); // execute http call
}
Send JSON:
RestClientFactory factory = new RestClientFactory();
try(RestClient restClient = factory.newRestClient()) { // new instance of RestClient
RestClientResponse response = restClient.post("https://somewhere.com") // API URL (http post)
.body("{\"username\" : \"John\"}", org.apache.http.entity.ContentType.APPLICATION_JSON) // request body
.execute(); // execute http call
}
Add custom header
RestClientFactory factory = new RestClientFactory();
try(RestClient restClient = factory.newRestClient()) {
RestClientResponse response = restClient.get("https://somewhere.com")
.header("headerName", "headerValue") // add http header
.execute(); // execute http call
}
License
Apache License 2.0