带有参数的 Spring RestTemplate HTTP Post 导致 400 错误请求错误
可能的重复 需要帮助 RestTemplate Post Request with Body Parameters? 和 Spring RESTtemplate POST 但这些答案对我
不起作用,我试图从 Spring Android 的 API 获取访问令牌。来自Instagram文档的请求是这样的:Instagram
curl \-F 'client_id=CLIENT-ID' \
-F 'client_secret=CLIENT-SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=YOUR-REDIRECT-URI' \
-F 'code=CODE' \https://api.instagram.com/oauth/access_token
这是我的请求访问令牌(在我成功获得请求令牌后):
MultiValueMap<String, String> mvm = new LinkedMultiValueMap<String, String>();
mvm.add("client_id", INSTAGRAM_CILENT_ID);
mvm.add("client_secret", INSTAGRAM_SECRET);
mvm.add("grant_type", "authorization_code");
mvm.add("redirect_uri", CALLBACKURL);
mvm.add("code", requestToken);
InstagramResult result = restTemplate .postForObject("https://api.instagram.com/oauth/access_token", mvm, InstagramResult .class);
结果映射类:
public class InstagramLogin {
public String access_token;
public InstagramUser user;
}
public class InstagramUser {
public String id;
public String username;
public String full_name;
public String profile_picture;
}
其余模板:
RestTemplate restTemplate = new RestTemplate();
final List<HttpMessageConverter<?>> listHttpMessageConverters = new ArrayList< HttpMessageConverter<?> >();
listHttpMessageConverters.add(new GsonHttpMessageConverter());
listHttpMessageConverters.add(new FormHttpMessageConverter());
listHttpMessageConverters.add(new StringHttpMessageConverter());
restTemplate.setMessageConverters(listHttpMessageConverters);
但我总是得到400个错误的请求错误。这是我的堆栈跟踪:
04-03 09:32:45.366: W/RestTemplate(31709): POST request for "https://api.instagram.com/oauth/access_token" resulted in 400 (BAD REQUEST); invoking error handler
04-03 09:32:46.857: E//DefaultRequestRunner.java:138(31709): 09:32:46.862 Thread-32787 An exception occurred during request network execution :400 BAD REQUEST
04-03 09:32:46.857: E//DefaultRequestRunner.java:138(31709): org.springframework.web.client.HttpClientErrorException: 400 BAD REQUEST
04-03 09:32:46.857: E//DefaultRequestRunner.java:138(31709): at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:76)
04-03 09:32:46.857: E//DefaultRequestRunner.java:138(31709): at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:524)
04-03 09:32:46.857: E//DefaultRequestRunner.java:138(31709): at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:481)
04-03 09:32:46.857: E//DefaultRequestRunner.java:138(31709): at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:439)
04-03 09:32:46.857: E//DefaultRequestRunner.java:138(31709): at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:317)
P/s:我肯定我的参数值是正确的,因为我通过curl进行了测试,它工作正常。