RestTemplate usage

半世苍凉 提交于 2019-12-04 01:42:47

问题


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:


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", "*/*");


来源:https://stackoverflow.com/questions/15107494/resttemplate-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!