Ice
Ice

Reputation: 1981

Consuming rest works with curl but does not work when I am usiing RestTemplate

I have an issue with RestTemplate, I want to consume https://swapi.co/api/

It works when I am using Curl:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET

But when I am trying to use RestTemplate it doesn't work.

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<?> entity = new HttpEntity<>(headers);


    HttpEntity<String> response = restTemplate.exchange("http://swapi.co/api/", HttpMethod.GET, entity, String.class);

    Root root = new Gson().fromJson(response.getBody(), Root.class);
    System.out.println(root);

As you can see I set Accept and ContentType like in curl command. What am I doing wrong, all time I am receiving 403 Forbidden Status? I am using spring boot with spring security, but I disable csrf mode.

Upvotes: 0

Views: 1794

Answers (3)

Barath
Barath

Reputation: 5283

Check the url it says https://swapi.co/api/ but above code points to HTTP.

HttpEntity<String> response = restTemplate.exchange("https://swapi.co/api/", HttpMethod.GET, entity, String.class);

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692121

Inspecting the response shows that the request goes through Cloudflare, and that the response contains the following error:

The owner of this website (swapi.co) has banned your access based on your browser's signature (3a4c8846af5169b2-ua21).

So you can cheat and add an accepted User-Agent header. For example:

headers.add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:55.0) Gecko/20100101 Firefox/55.0");

You should contact the owner/maintainer/developer of swapi to add a section about that limitation in the documentation, because it's far from being obvious, and should definitely be documented.

Upvotes: 2

Urosh T.
Urosh T.

Reputation: 3824

Simply use restTemplate.getForObject("http://swapi.co/api/", String.class); (Returns a string). It is much more straightforward and self-explanatory.

The 403 you are getting must be something related to your headers, most likely the line that says headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON))

Upvotes: 0

Related Questions