¿Cómo extraer el código de estado HTTP de la llamada RestTemplate a una URL?


Estoy usando RestTemplate para hacer una llamada HTTP a nuestro servicio que devuelve una respuesta JSON simple. No necesito analizar ese JSON para nada. Solo necesito devolver lo que sea que esté recibiendo de ese servicio.

Así que estoy mapeando eso a String.class y devolviendo el JSON response real como una cadena.

RestTemplate restTemplate = new RestTemplate();

String response = restTemplate.getForObject(url, String.class);

return response;

Ahora la pregunta es -

Estoy tratando de extraer HTTP Status codes después de golpear la URL. ¿Cómo puedo extraer el código de estado HTTP del código anterior? ¿Necesito hacer algún cambio en eso en ¿cómo lo hago actualmente?

Actualizar:-

Esto es lo que he intentado y también puedo obtener la respuesta y el código de estado. Pero ¿siempre necesito establecer HttpHeaders y Entity objeto como a continuación lo estoy haciendo?

    RestTemplate restTemplate = new RestTemplate();     

    //and do I need this JSON media type for my use case?
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    //set my entity
    HttpEntity<Object> entity = new HttpEntity<Object>(headers);

    ResponseEntity<String> out = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

    System.out.println(out.getBody());
    System.out.println(out.getStatusCode());

Un par de preguntas - Necesito tener MediaType.APPLICATION_JSON como solo estoy haciendo una llamada a url que devuelve una respuesta, puede devolver JSON o XML o cadena simple.

Author: john, 2014-04-22

4 answers

Utilice el RestTemplate#exchange(..) métodos que devuelven una ResponseEntity. Esto le da acceso a la línea de estado y los encabezados (y el cuerpo, obviamente).

 21
Author: Sotirios Delimanolis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-21 20:23:16

Si no desea dejar la abstracción agradable alrededor de RestTemplate.get/postForObject... métodos detrás como me y no le gusta jugar con las cosas repetitivas necesarias cuando se utiliza RestTemplate.exchange... (Request - and ResponseEntity, HttpHeaders, etc), hay otra opción para obtener acceso a los códigos HttpStatus.

Simplemente rodea el RestTemplate.get/postForObject... habitual con un try / catch para org.springframework.web.client.HttpClientErrorException y org.springframework.web.client.HttpServerErrorException, como en este ejemplo:

try {
    return restTemplate.postForObject("http://your.url.here", "YourRequestObjectForPostBodyHere", YourResponse.class);

} catch (HttpClientErrorException | HttpServerErrorException httpClientOrServerExc) {

    if(HttpStatus.NOT_FOUND.equals(httpClientOrServerExc.getStatusCode())) {
      // your handling of "NOT FOUND" here  
      // e.g. throw new RuntimeException("Your Error Message here", httpClientOrServerExc);
    }
    else {
      // your handling of other errors here
}

El org.springframework.web.client.HttpServerErrorException se añade aquí para los errores con un 50x.

Ahora eres capaz de simple reaccione a todos los StatusCodes que desee, excepto el apropiado, que coincida con su método HTTP, como GET y 200, que no se manejará como excepción, ya que es el que coincide. Pero esto debería ser sencillo, si estás implementando / consumiendo servicios RESTful:)

 2
Author: jonashackt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-27 12:42:53

Puede haber algunos casos de uso ligeramente más complicados en los que alguien podría caer (como lo hice). Considere lo siguiente:

Soporta un objeto Page para usarlo con RestTemplate y Parametrizedtypereference :

RestPageResponse :

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

public class RestResponsePage<T> extends PageImpl<T>{

  private static final long serialVersionUID = 3248189030448292002L;

  public RestResponsePage(List<T> content, Pageable pageable, long total) {
    super(content, pageable, total);
  }

  public RestResponsePage(List<T> content) {
    super(content);
  }

  public RestResponsePage() {
    super(new ArrayList<T>());
  }

} 

Usando ParameterizedTypeReference se obtiene lo siguiente:

ParameterizedTypeReference<RestResponsePage<MyObject>> responseType = 
new ParameterizedTypeReference<RestResponsePage<MyObject>>() {};
HttpEntity<RestResponsePage<MyObject>> response = restTemplate.exchange(oauthUrl, HttpMethod.GET, entity, responseType);

Llamando a #exchange :

HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<?> entity = new HttpEntity<>(headers);

response = restTemplate.exchange("localhost:8080/example", HttpMethod.GET, entity, responseType);

Aquí está la parte "complicada".

Intentar llamar a exchange getStatusCode será imposible porque el compilador, desafortunadamente, no será consciente del tipo" pretendido " de response.

Esto se debe a que los genéricos se implementan a través de la eliminación de tipos que elimina toda la información relativa a los tipos genéricos durante la compilación (leer más - fuente)

((ResponseEntity<RestResponsePage<MyObject>>) response).getStatusCode()

En este caso, usted tiene que convertir explícitamente la variable a la clase deseada para obtener el statusCode (y/u otros atributos)!

 0
Author: Menelaos Kotsollaris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-05 20:07:43
private RestTemplate restTemplate = new RestTemplate();

ResponseEntity<String> response = restTemplate.exchange(url,HttpMethod.GET, requestEntity,String.class);

La respuesta contiene 'body', 'headers'y' statusCode '

Para obtener statusCode : response.getStatusCode ();

 0
Author: santosh kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-27 15:52:21