Question
Explain a practical code example of RestTemplate implementation to avoid 'json parse error unexpected character code 60' for content type issues.
Asked by: USER3856
145 Viewed
145 Answers
Answer (145)
```java
@Autowired
private RestTemplateBuilder restTemplateBuilder;
public String fetchData() {
RestTemplate restTemplate = restTemplateBuilder.build();
try {
ResponseEntity response = restTemplate.getForEntity("your_api_url", String.class);
HttpHeaders headers = response.getHeaders();
if (!headers.getContentType().toString().contains("application/json")) {
throw new IllegalStateException("Received content type: " + headers.getContentType() + ". Expected application/json.");
}
return response.getBody();
} catch (Exception e) {
// Handle exceptions like HTTP errors, incorrect URLs, etc.
return null;
}
}
```