Reputation: 313
I'm struggling with RestTemplate. I need to POST some authentication information to a rest webservice. I can send a request and I get a response. But according to the response my header parameters are not getting through. (Sending the same request with SOAPUI works fine)
This is my code:
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);
Anyone who can tell me what's wrong with my HttpEntity or HttpHeader?
thank you.
SOLVED:
Ok, finally got it working.
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);
Because I also had a hard time on the response, maybe it can be useful to others:
@JsonIgnoreProperties(ignoreUnknown = true)
public class ItcLoginResponse {
public String loginToken;
@JsonProperty("token")
public String getLoginToken() {
return loginToken;
}
public void setLoginToken(String loginToken) {
this.loginToken = loginToken;
}
}
Upvotes: 30
Views: 77173
Reputation: 7048
You're setting a header indicating you're posting a form (APPLICATION_FORM_URLENCODED), but then setting companyId and password as HTTP headers.
I suspect you want those fields to be in the body of your request.
You're also creating an HttpEntity<String>
which indicates you're going to post a request body containing a String, but you're providing headers but no String.
If that doesn't help you fix it perhaps you can explain what the request is supposed to look like.
Upvotes: 6