我在 Java 和 Spring Boot 專案中使用 RestTemplate 客戶端,當我收到來自服務器的回應正文時,我有以下代碼:
private RestTemplate oauth2RestTemplate;
private ParameterizedTypeReference<List<Employee>> parameterizedTypeReference;
....
ResponseEntity<List<Employee>> rtGetResponse = oauth2RestTemplate.exchange(uriComponents.toUri(), HttpMethod.GET, httpEntity, parameterizedTypeReference);
所以在這種情況下,我會收到一份員工名單。
現在我想使用這種方法,但來自服務器的回應正文是void,我想使用交換方法,但我不知道用什么來代替 parameterizedTypeReference 因為回應是無效的。所以我沒有回應體,我只想捕捉例外。
可以做這樣的事情嗎?
try {
oauth2RestTemplate.exchange(uriComponents.toUri(), HttpMethod.GET, httpEntity, null);
} catch (HttpStatusCodeException e) {
switch (e.getStatusCode()) {
case BAD_REQUEST:
throw new BadRequestException(e);
case NOT_FOUND:
throw new NotFoundException(e);
...
}
}
uj5u.com熱心網友回復:
你可以使用Void類
try {
oauth2RestTemplate.exchange(uriComponents.toUri(), HttpMethod.GET, httpEntity, Void.class);
} catch (HttpStatusCodeException e) {
switch (e.getStatusCode()) {
case BAD_REQUEST:
throw new BadRequestException(e);
case NOT_FOUND:
throw new NotFoundException(e);
...
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/417594.html
標籤:
上一篇:在微服務架構中,在一個服務的內部客戶端之間共享請求和回應合約的好方法是什么
下一篇:當我有2個具有相同端點字串值的控制器方法時,為什么會出現“requestMappingHandlerMapping”錯誤
