如何从RestTemplate调用URL中提取HTTP状态代码?

joh*_*ohn 39 java url http-status-codes resttemplate

RestTemplate用来对我们的服务进行HTTP调用,返回一个简单的JSON响应.我根本不需要解析那个JSON.我只需要返回我从该服务中获得的任何内容.

所以我将其映射到String.class并将实际值JSON response作为字符串返回.

RestTemplate restTemplate = new RestTemplate();

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

return response;
Run Code Online (Sandbox Code Playgroud)

现在的问题是 -

我想HTTP Status codes在点击URL后提取.如何从上面的代码中提取HTTP状态代码?我是否需要以目前的方式对其进行任何更改?

更新: -

这是我尝试过的,我能够得到回复和状态代码.但是,我是否总是需要设置HttpHeadersEntity对象,如下所示我在做什么?

    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());
Run Code Online (Sandbox Code Playgroud)

几个问题 - 我需要有,MediaType.APPLICATION_JSON因为我只是调用url返回响应,它可以返回JSON或XML或简单的字符串.

Sot*_*lis 35

使用RestTemplate#exchange(..)返回的方法ResponseEntity.这使您可以访问状态行和标题(显然是身体).

  • @ user2809564阅读javadoc.它准确地解释了您需要做什么. (2认同)

jon*_*ckt 10

如果你不想把RestTemplate.get/postForObject...像我这样的方法留下好的抽象并且不喜欢使用在使用时需要的样板文件RestTemplate.exchange...(Request-和ResponseEntity,HttpHeaders等),那么还有另一个选项可以访问HttpStatus码.

只是围绕通常RestTemplate.get/postForObject...用一个try/catch为org.springframework.web.client.HttpClientErrorExceptionorg.springframework.web.client.HttpServerErrorException,就像这个例子:

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
}
Run Code Online (Sandbox Code Playgroud)

org.springframework.web.client.HttpServerErrorException这里添加的是a的错误50x.

现在you're能简单应对所有你想要的StatusCodes -除了一个合适的,符合你的HTTP方法-像GET200,这不会致使被作为例外处理,因为它是一个匹配.但是,如果您正在实施/使用RESTful服务,这应该是直截了当的:)

  • 我不明白你的意思 - 不同的 HTTP 代码然后 `200` 由 Spring 通过异常自动表示,我不会在这里“创建”它们或其他东西。“验证成功的请求‘200’”是什么意思?你可以在 `restTemplate.postForObject()` 方法调用之后做任何事情——这正是 `200` 状态的表示,因为所有其他状态都将(并由 Spring 表示)作为异常。 (3认同)
  • 只是为了获取响应代码而引发异常是一个非常阴暗的解决方法......正如您在回答中所写的那样,您无法验证成功的请求“200” (2认同)
  • 1xx 和 3xx 的 @jonashackt 也将是例外? (2认同)

Mat*_*bin 7

如果您想要来自 RestTemplate 的所有 HTTPStatus,包括 4XX 和 5XX,则必须向 restTemplate 提供一个 ResponseErrorHandler,因为默认处理程序将在 4XX 或 5XX 的情况下抛出异常

我们可以这样做:

RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
    @Override
    public boolean hasError(HttpStatus statusCode) {
        return false;
    }
});

ResponseEntity<YourResponse> responseEntity =
    restTemplate.getForEntity("http://your.url.here", YourResponse.class);
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.XXXX);
Run Code Online (Sandbox Code Playgroud)


小智 5

private RestTemplate restTemplate = new RestTemplate();

ResponseEntity<String> response = restTemplate.exchange(url,HttpMethod.GET, requestEntity,String.class);
Run Code Online (Sandbox Code Playgroud)

响应包含“body”、“headers”和“statusCode”

获取状态代码:response.getStatusCode();