我正在尝试在没有请求正文的情况下创建restTemplate.postForObject(),并且我收到了错误的请求。
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<>(headers);
CurrentAccount account = client.postForObject(
"https://api.dropboxapi.com/2/users/get_current_account", entity, CurrentAccount.class);
错误
Caused by: org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: [Error in call to API function "users/get_current_account": Bad HTTP "Content-Type" header: "application/x-www-form-urlencoded". Expecting one of "application/json", "application/json; charset=utf-8", "text/plain; charset=dropbox-cors-hack".]
添加时
headers.setContentType(MediaType.APPLICATION_JSON);
我收到错误
Caused by: org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: [Error in call to API function "users/get_current_account": request body: could not decode input as JSON]
邮递员请求在没有身体的情况下起作用
答案 0 :(得分:1)
该错误消息非常不言自明。您已经设置了Accept
,但没有设置Content-Type
在标题中添加以下内容
import org.springframework.http.MediaType;
...
headers.setContentType(MediaType.APPLICATION_JSON);
答案 1 :(得分:1)
您还应该将请求正文指定为字符串文本“ null” 。是的,Dropbox Api表示发出POST请求时不需要发送主体,但是在POST请求中Dropbox如何期望空JSON主体表示与spring rest模板如何发送空主体JSON表示之间存在错误。
答案 2 :(得分:0)
您可以将org.json.JSONObject用作空请求正文:
restTemplate.postForEntity(
"http://<yoururl>.com",
new org.json.JSONObject(), <YourResponseType>.class).getBody();
尤其是如果您希望路由返回某些内容,在这种情况下,“空”请求正文将不起作用。