我有 2 個springbootREST API REST-A 和 REST-B。REST-B 正在與mongodbCRUD 操作互動。REST-A 出于不同的原因呼叫 REST-B 端點。
REST-B 中的控制器(客戶 API)
public class CustomerController {
@Autowired
private CustomerRepository customerRepository;
@GetMapping(value = "/customers/{id}")
public ResponseEntity<Customer> getCustomerByExternalReferenceId(@PathVariable(value = "id") String id)
throws ResourceNotFoundException {
System.out.println("Customer id received :: " id);
Customer customer = customerRepository.findByExternalCustomerReferenceId(id)
.orElseThrow(() -> new ResourceNotFoundException("Customer not found for this id :: " id));
return ResponseEntity.ok().body(customer);
}
}
如果我在 DB 中找到客戶和在 DB 中找不到客戶,我從郵遞員那里呼叫此端點作業正常。


現在,如果我嘗試從 REST-A 呼叫相同的端點,并且如果客戶在 DB 中找到,我可以獲得回應。
String url = "http://localhost:8086/customer-api/customers/{id}";
String extCustRefId =
setupRequest.getPayload().getCustomer().getCustomerReferenceId();
// URI (URL) parameters
Map<String, String> urlParams = new HashMap<>();
urlParams.put("id", extCustRefId); // here I tried with id that exists in DB and getting 200 ok response
HttpHeaders headers = new HttpHeaders();
headers.set("X-GP-Request-Id", "abc-xyz-123");
headers.set("Content-Type", "application/json");
headers.set("Accept", "application/json");
headers.set("Content-Length", "65");
String searchurl = UriComponentsBuilder.fromUriString(url).buildAndExpand(urlParams).toString();
System.out.println(searchurl);
HttpEntity request = new HttpEntity(headers);
RestTemplate restTemplate = new RestTemplate();
try {
ResponseEntity<String> response = restTemplate.exchange(
searchurl,
HttpMethod.GET,
request,
String.class
);
} catch (Exception e) {
e.printStackTrace();
}
但是如果沒有從 REST-B(客戶 API)中找到客戶,那么我得到
http://localhost:8086/customer-api/customers/customer-528f2331-d0c8-46f6-88c2-7445ee6f4821
Customer id received :: customer-528f2331-d0c8-46f6-88c2-7445ee6f4821
org.springframework.web.client.HttpClientErrorException: 404 null
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:78)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
如何從一個springboot應用程式呼叫其余端點并正確處理回應?
uj5u.com熱心網友回復:
您可以從HttpClientErrorException以下位置獲取回應正文:
try {
ResponseEntity<String> response = restTemplate.exchange(
searchurl,
HttpMethod.GET,
request,
String.class
);
} catch (HttpClientErrorException e) {
String errorResponseBody = e.getResponseBodyAsString();
e.printStackTrace();
}
然后,您可以使用 JacksonObjectMapper將 String 映射到 Java 物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/335973.html
上一篇:SpringBoot/Java:如何在物件Map<String,Map<String,Map<String,Long>>>中計算Item并獲取結果
