简体   繁体   中英

Spring rest template get for entity giving 400 error

I'm getting the following exception org.springframework.web.client.HttpClientErrorException: 400 Bad Request

on this statement final ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:12001/api/profiles/bymsisdn/0747894146", String.class);

But I'm getting successful response using curl url -X GET " http://localhost:8001/api/profiles/bymsisdn/0747894146 "

Extra notes: resttemplate = new RestTemplate(); // No Headers or extra convertors added as I think it's not required because using curl works fine resttemplate = new RestTemplate(); // No Headers or extra convertors added as I think it's not required because using curl works fine

You can use requestbin to test how your http client performs.

I think RestTemplate is putting Accept header for which your server responds 400. So you may need to edit your request headers:

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
restTemplate.exchange("http://localhost:12001/api/profiles/bymsisdn/0747894146", HttpMethod.GET, entity, String.class);

Note that this is a tentative solution, adapt to your server.

curl uses / as the Accept header when you do not specify one. With RestTemplate if you do not specify the accept header , it attempts to find a suitable MIME type to your response type (in your case String). For String class depending on your configuration can match text/* MIME types which might not match what the target endpoint produces.

Try to explictly specify the content type that you need to handle using the exchange overloaded methods of RestTemplate

final String uri = http://localhost:8088/myapp/ {data}";

RestTemplate restTemplate = new RestTemplate();

MyResponse result = restTemplate.getForObject(uri,MyResponse.class,valData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM