My project consist of 5 modules. And only one of them uses JAX-RS, others use Spring. My current task is develop service, that will be send HTTP requests to some API. I wanna use Spring RestTemplate
for this task, but problem is project with JAX-RS haven't RestTemplate
class and other needfull dependencies. I wanna use:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
in the JAX-RS module, to avoid code duplicating for RestTemplate
and for some JAX-RS client. Is it good idea? Will be RestTemplate
work properly without spring-core
dependency?
To use RestTemplate
you need just the spring-web
dependency:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
The spring-web
dependency has spring-core
as a transitive dependency.
To use RestTemplate
it's as simple as:
public class ExampleWithRestTemplate {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response =
restTemplate.getForEntity("http://date.jsontest.com", String.class);
System.out.println(response.getBody());
}
}
Instead of RestTemplate
you also could consider JAX-RS 2.0 Client API to consume REST web services. Jersey is the JAX-RS reference implementation and offers a great API.
To use Jersey Client API, the following dependency is required:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.23.2</version>
</dependency>
For more details, have a look at the documentation.
You also could consider the Jersey Client Proxy API. The basic idea of this approach is to attach the standard JAX-RS annotations to an interface, and then implement that interface by a resource class on the server side while reusing the same interface on the client side by dynamically generating an implementation of that using java.lang.reflect.Proxy
calling the right low-level client API methods.
To use the Jersey Client Proxy API, the following dependency is required:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-proxy-client</artifactId>
<version>2.23.2</version>
</dependency>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With