3

我正在尝试使用RestTemplate以制作PUT. 出于某种原因,我无法重现PUT我使用curl它创建的内容,并且没有任何问题。

这是我的curl调用成功并返回 200:

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

这是试图复制此curl调用的 Java 代码。在我的情况下,此代码将抛出HttpClientErrorExceptionstatus = 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();

这些请求有什么区别?如何将 Java 版本收敛到curl版本?

4

1 回答 1

1

阿格尔,太愚蠢了。缺少的部分是Accept标题。显然默认curl添加Accept: */*。它可能是期望正确Accept标头的端点实现。添加这一行解决了这个问题:

headers.add("Accept", "*/*");
于 2013-02-27T11:41:37.873 回答