@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;
}
}
}
error message:
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.
I got the same error message because I forgot to include the request body when moving from api client to code (Bruno -> Bun/Svelte/Wretch).
I don't know Java or Spring Boot, but my guess would be that the request body is missing or malformed. Have you tried using
Content-Type: application/json
? The AFKLM api responds withapplication/hal+json
, but I'm not aware of any endpoints that expect it.