Error when requesting API

Asked

Viewed 129 times

0

I’m getting an error, possibly from CORS, when making a GET for an API, which is a third-party API and I don’t have how to release server-side CORS:

Exception in thread "main" org.springframework.web.client.Resourceaccessexception: I/O error on GET request for "https://api.cartolafc.globo.com/time/id/17886329/1": Unexpected end of file from server; nested Exception is java.net.Socketexception: Unexpected end of file from server

I am consuming an API using Resttemplate as follows:

public class FamiliabomdebolaApplication {

    public static void main(String[] args) {
        SpringApplication.run(FamiliabomdebolaApplication.class, args);


        RestTemplate template = new RestTemplate();

        UriComponents uri = UriComponentsBuilder.newInstance().scheme("https").host("api.cartolafc.globo.com")
                .path("time/id/17886329/1")
                // .queryParam("fields", "all")
                .build();

        ResponseEntity<Time> entity = template.getForEntity(uri.toUriString(), Time.class);

        System.out.println(entity.getBody().getEsquema_id());

    }

}

Can anyone help me? I’ve heard something about using proxy, but I don’t know how to implement it in Java/Spring

1 answer

1


Only add a User-Agent in the request that it will work.

private static HttpHeaders createHttpHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("User-Agent", "PostmanRuntime/7.26.2");
    return headers;
}

private static void fazerRequest() {
    UriComponents uri = UriComponentsBuilder.newInstance().scheme("https").host("api.cartolafc.globo.com")
                                            .path("time/id/17886329/1")
                                            // .queryParam("fields", "all")
                                            .build();
    RestTemplate restTemplate = new RestTemplate();
    try {
        HttpHeaders headers = createHttpHeaders();
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(uri.toUri(), HttpMethod.GET, entity, String.class);
        System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
    }
    catch (Exception eek) {
        System.out.println("** Exception: "+ eek.getMessage());
    }
}

If you test in Postman you will see that endpoint does not accept requests without a user-agent which ends up causing the server to refuse your request.

  • Perfect, Emerson. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.