RestTemplate gives 400 Bad Request Error on a Get Request

Viewed 10454

When I try to make a get request with Spring's RestTemplate, it gives 400 BAD Request. I can call the same url from javascript successfully with the headers below :

enter image description here

But the code below does not work. What might be the cause?

public Entity getEntityByUri(String uri) {
        String req = "http://live.dbpedia.org/sparql?query=DESCRIBE%20%3Chttp://dbpedia.org/resource/Concept_learning%3E&format=application%2Fjson-ld";
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.ALL));

    HttpEntity<String> httpEntity = new HttpEntity<String>(headers);

    new RestTemplate().exchange(req, HttpMethod.GET, httpEntity, Map.class);

    Entity entity = new Entity();
    return entity;
}
3 Answers

Anyone getting same error make sure your URL is decoded means no percent symbols in url (if space in param values).

This worked for me

    try {
        requestURL = URLDecoder.decode("http://api.com?p=1&groups=3212&affected-since=2019-06-06T14%3A11%3A14.880&detail=full&after-id=43536", "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } 

Maybe

headers.setAccept(Arrays.asList(MediaType.ALL));

generates a malformed "Accept" header field? (FWIW, why do you send it at all???)

Related