我正在为 RestTemplate 苦苦挣扎。我需要将一些身份验证信息发布到休息网络服务。我可以发送请求并得到响应。但是根据响应,我的标头参数没有通过。(使用 SOAPUI 发送相同的请求可以正常工作)
这是我的代码:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("companyId", companyId);
headers.add("password", password);
HttpEntity<String> request = new HttpEntity<String>(headers);
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);
LoginResponse response = (LoginResponse)restTemplate.postForObject(url, request, LoginResponse.class);
谁能告诉我我的 HttpEntity 或 HttpHeader 有什么问题?
谢谢你。
解决了:
好的,终于搞定了。
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("companyId", companyId);
map.add("password", password);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new MappingJacksonHttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);
LoginResponse response = (LoginResponse) restTemplate.postForObject(url, request, LoginResponse.class);
因为我也很难回应,也许它对其他人有用:
@JsonIgnoreProperties(ignoreUnknown = true)
public class ItcLoginResponse {
public String loginToken;
@JsonProperty("token")
public String getLoginToken() {
return loginToken;
}
public void setLoginToken(String loginToken) {
this.loginToken = loginToken;
}
}