How to CONSUME a REST web service with Spring (Java)?

2

Good morning. My question is, how can I consume a REST web service from my application that is made with spring framework ?. The spring documentation tells me that I can do it with restTemplate. For example to obtain data:

restTemplate.getForObject(uri,class,200);

but I get this error

org.springframework.web.client.HttpClientErrorException: 403 Forbidden
    
asked by devjav 27.07.2016 в 16:05
source

3 answers

1

Error 403 is given in response to a client from a web page or service to indicate that the server refuses to allow the requested action.

Typically, it's because the service is secured and can not be invoked as you are doing.

RestTemplate supports basic authentication for example and you could do something like this:

HttpComponentsClientHttpRequestFactory requestFactory = 
(HttpComponentsClientHttpRequestFactory) restTemplate.getRequestFactory(); 
DefaultHttpClient httpClient = (DefaultHttpClient) 
requestFactory.getHttpClient();
 httpClient.getCredentialsProvider().setCredentials(
 new AuthScope(host, port, AuthScope.ANY_REALM),
 new UsernamePasswordCredentials("name", "pass"));

And then you could call the Rest service as follows:

restTemplate.exchange("http://localhost:8080/spring-security-rest-template/api/foos/1", HttpMethod.GET, null, Foo.class) ;

The apache dependency httpcomponents must be included in addition to the spring-mvc.

<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.3.5</version>
</dependency>
    
answered by 24.10.2016 в 16:54
0

If the API does not require authentication, the error is in the implementation. Here is the functional code that obtains the data of the URL that you specify.

@Test    
public void test_whenList() {
            RestTemplate rt = new RestTemplate();
            ResponseEntity<List<Response>> exchange = rt.exchange("https://jsonplaceholder.typicode.com/posts",
                    HttpMethod.GET, null, new ParameterizedTypeReference<List<Response>>() {
                    });
            List<Response> body = exchange.getBody();
            Response response = body.stream().findFirst().orElse(null);
            assertThat(response.getUserId(), is(1));

        }

@Test
public void test_whenObject() {
    RestTemplate rt = new RestTemplate();
    ResponseEntity<Response> exchange = rt.exchange("https://jsonplaceholder.typicode.com/posts/4", HttpMethod.GET,
            null, Response.class);
    Response response = exchange.getBody();
    assertThat(response.getId(), is(4));

}

The response object is according to the API:

public Response() {
    super();
}

private Integer userId;
private Integer id;
private String title;
private String body;
    
answered by 01.05.2018 в 20:12
-1

It is a security protection you need to disable CSRF, or verify what type of security or credence the web service uses the required request

    
answered by 29.07.2016 в 18:20