私はこの方法でサービスを消費しようとしています:
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
public class StatesAPI {
private RestTemplate restTemplate;
private String apiEndpoint = "http://service/Geo.svc/getsomethingJson?format=json";
public static void main(String[] args) {
StatesAPI s = new StatesAPI();
s.foo("CA");
}
public void foo(String state) {
String requestBody = "{\"statename\":\"" + state + "\"}";
String apiResponse = getRestTemplate().postForObject(apiEndpoint,
requestBody, String.class);
System.out.println(apiResponse);
}
public RestTemplate getRestTemplate() {
// TODO: Fix the RestTemplate to be a singleton instance.
restTemplate = (this.restTemplate == null) ? new RestTemplate()
: restTemplate;
HttpMessageConverter<?> formHttpMessageConverter = new FormHttpMessageConverter();
HttpMessageConverter<?> stringHttpMessageConverternew = new StringHttpMessageConverter();
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(formHttpMessageConverter);
converters.add(stringHttpMessageConverternew);
restTemplate.setMessageConverters(converters);
return restTemplate;
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
}
しかし、実行すると次のエラーが発生しました。
09/10/2013 10:10:32 AM org.springframework.web.client.RestTemplate handleResponseError
ADVERTENCIA: POST request for "[here the link in the code]" resulted in 400 (Bad Request); invoking error handler
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 400 Bad Request
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:76)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:486)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:443)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:401)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:279)
at StatesAPI.foo(StatesAPI.java:20)
at StatesAPI.main(StatesAPI.java:15)