@Service
public class AirService {
@Value("${api.key}")
private String apiKey;
@Value("${api.url}")
private String apiUrl;
@Autowired
private RestTemplate restTemplate;
@Autowired
private HttpHeaders httpHeaders;
Logger logger = LoggerFactory.getLogger(AirService.class);
public double fetchTotalPrice() {
logger.info("Fetching total price from Air France API...");
httpHeaders.set("Content-Type", "application/hal+json");
httpHeaders.set("API-Key", "apiKey");
httpHeaders.set("AFKL-TRAVEL-Host", "KL");
HttpEntity<String> entity = new HttpEntity<>(httpHeaders);
logger.info("Sending request to API: {}", apiUrl);
logger.info("Request body: {}", httpHeaders);
try {
ResponseEntity<FlightResponse> responseEntity = restTemplate.exchange(apiUrl, HttpMethod.POST, entity, FlightResponse.class);
logger.info("Received response from API: {}", responseEntity);
logger.info("Response status code: {}", responseEntity.getStatusCode());
if (responseEntity.getStatusCode().is2xxSuccessful()) {
FlightResponse ApiResponse = responseEntity.getBody();
double totalPrice = airFranceApiResponse
.getDestinationCities()
.get(0)
.getFlightProducts()
.get(0)
.getPrice()
.getTotalPrice();
logger.info("Total price retrieved: {}", totalPrice);
return totalPrice;
} else {
logger.error("Error fetching total price: {}", responseEntity.getStatusCodeValue());
return 0;
}
} catch (Exception e) {
logger.error("Unexpected error occurred", e);
return 0;
}
}
}
错误信息:
org.springframework.web.client.HttpClientErrorException$BadRequest: 400 : "{"errors":[{"code":2000,"name":"OFA/TECHNICAL/CLIENT_ERROR","description":"Unreadable message"}]}" I am trying to fetching data from open Api, I am sure the headers.I use same request for Postman and it works but I couldn't implement truley spring boot.
我收到了同样的错误消息,因为我在从 api 客户端转移到代码时忘记包含请求正文(Bruno -> Bun/Svelte/Wretch)。
我不了解 Java 或 Spring Boot,但我的猜测是请求正文丢失或格式错误。您尝试过使用
Content-Type: application/json
吗? AFKLM api 响应为 application/hal+json
,但我不知道有任何端点需要它。