【问题标题】:When HttpStatusCodeException exception raised?何时引发 HttpStatusCodeException 异常?
【发布时间】:2018-06-03 02:42:50
【问题描述】:

当我使用下面的代码时,出现HttpStatusCodeException 异常的情况是什么。

ResponseEntity<Object> response = 
  restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, entity, Object.class);

有谁能帮忙吗??????

【问题讨论】:

  • 我需要创建引发 HttpStatusCodeException 的案例。

标签: java spring rest httpexception


【解决方案1】:

HTTP 状态代码是来自服务器的响应,因此如果您可以控制服务器,那么您可以让它返回您想要的任何错误。如果您无法控制服务器,那么您可以尝试发送错误/无效请求,以便服务器会抱怨。

在你的服务器端是这样的:

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getAnError() {
    // complain!
    return ResponseEntity.status(HttpStatus.FORBIDDEN);
}

【讨论】:

  • BodyBuilder bodyBuilder = ResponseEntity.status(HttpStatus.BAD_GATEWAY); ResponseEntity response = bodyBuilder.build();我这样用过,但没用
  • @Nag-Raj 已编辑。尝试类似的方法。
【解决方案2】:

根据文档,HttpStatusCodeExceptionHttpClientErrorExceptionHttpServerErrorException 有两种类型。

  • 收到 HTTP 4xx 时抛出前者。
  • 后者在收到 HTTP 5xx 时抛出。

所以你可以使用 ResponseEntity.BodyBuilder.status(505) 例如在你的

中提出HttpServerErrorException

【讨论】:

  • BodyBuilder bodyBuilder = ResponseEntity.status(HttpStatus.BAD_GATEWAY); ResponseEntity response = bodyBuilder.build();我这样用过但没用
【解决方案3】:

在spring-web库的3.1.0.RELEASE中添加了org.springframework.web.client.RestTemplate类的exhange(...)方法。

此方法会引发 RestClientException,其中涵盖客户端 (4_xx) 和服务器 (5_xx) 端 http 代码错误。但是RestClientException 不提供getStatusCode(), getResponseAsString() 等方法。

  1. HttpsStatusCodeExceptionRestClientException 的子代,它正在做同样的事情,但使用了 getStatusCode(), getResponseAsString() 等其他方法。

  2. HttpClientErrorExceptionHttpsStatusCodeException 的子级,只处理客户端错误 (4_xx) 而不是服务器错误。

  3. HttpServerErrorExceptionHttpsStatusCodeException 的子级,只处理服务器错误 (5_xx) 而不是客户端错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 2011-12-14
    • 2012-10-16
    • 2014-10-25
    • 2012-02-11
    • 2014-11-07
    • 2021-06-15
    相关资源
    最近更新 更多