Java RestTemplate.postForObject - 错误:org.springframework.web.client.HttpClientErrorException:400 错误请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19276190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:38:16  来源:igfitidea点击:

RestTemplate.postForObject - Error: org.springframework.web.client.HttpClientErrorException: 400 Bad Request

javaspringrestresttemplate

提问by Angelo Gabriel Escudero Vía

I'm trying to consume a service in this way:

我正在尝试以这种方式使用服务:

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;
    }
}

but when I run it I got this error:

但是当我运行它时,我收到了这个错误:

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)

回答by nilesh

I think you are missing headers and proper request body. Try this,

我认为您缺少标头和正确的请求正文。尝试这个,

    public void foo(String state) {
        MultiValueMap<String, Object> headers = new LinkedMultiValueMap<String, Object>();
        headers.add("Accept", "application/json");
        headers.add("Content-Type", "application/json");
        String requestBody = "{\"statename\":\"" + state + "\"}";
        HttpEntity request = new HttpEntity(requestBody, headers);
            String apiResponse = getRestTemplate().postForObject(apiEndpoint,
                    request, String.class);
            System.out.println(apiResponse);
     }

回答by TrueCoke

Try these modifications to your getRestTemplate:

尝试对 getRestTemplate 进行以下修改:

public RestTemplate getRestTemplate() {
    // TODO: Fix the RestTemplate to be a singleton instance.
    restTemplate = (this.restTemplate == null) ? new RestTemplate() : restTemplate;

    // Set the request factory. 
    // IMPORTANT: This section I had to add for POST request. Not needed for GET
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

    // Add converters
    // Note I use the Hymanson Converter, I removed the http form converter 
    // because it is not needed when posting String, used for multipart forms.
    restTemplate.getMessageConverters().add(new MappingHymanson2HttpMessageConverter());

    return restTemplate;
}