RestTemplate usage

2019-02-19 05:09发布

I'm trying to use RestTemplate in order to make a PUT. For some reason I can't reproduce the PUT I created using curl that goes through without any problems.

Here is my curl call that succeeds and returns 200:

curl https://www.exampe.com \
  -X PUT \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <bearer-token>" \
  -v \
  -d '{"json":"object"}'

And here is Java code that tried to replicate this curl call. This code in my case will throw HttpClientErrorException with status = 406:

boolean result = false; 
String url = "https://www.example.com";
String json = "{\"json\":\"object\"}";

RestTemplate rest = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
headers.add("Authorization", String.format("Bearer %s", authToken));

HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);
ResponseEntity<String> responseEntity = 
        rest.exchange(url, HttpMethod.PUT, requestEntity, String.class);

HttpStatus status = responseEntity.getStatusCode();

What's the difference between these requests? How do I converge the Java version to the curl version?

1条回答
在下西门庆
2楼-- · 2019-02-19 05:29

Agghr, so stupid. the missing part was the Accept header. Apparently curl adds Accept: */* by default. It's probably the endpoint implementation that expected proper Accept header. Adding this line solved the problem:

headers.add("Accept", "*/*");
查看更多
登录 后发表回答