Spring RESTtemplate POST

2019-07-16 13:28发布

I am using the Spring Framework and trying to do a post request. My post method takes the url, the HttpMethod, and the parameters that go into the body of the request.

NOTE: The var URL passed in network.POSTRequest( URL, ..,...) is different for each call.

Now, if I call this method with one parameter like so...(it works beautifully!)

//with one parameter
MultiValueMap<String, String> postParams = new LinkedMultiValueMap<String, String>();
postParams.add("id", "524cd432539ed");
network.POSTRequest( URL, HttpMethod.POST, postParams );

,but if there are two parameters like so....(it throws this error)

org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error

//with two parameters
MultiValueMap<String, String> postParams = new LinkedMultiValueMap<String, String>();
postParams.add("id", "crisp");
postParams.add("name", "honey");
network.POSTRequest( URL, HttpMethod.POST, postParams );

This is the POSTRequest method

public Object POSTRequest( String URL, HttpMethod method, MultiValueMap<String, String> postParams ){
            HttpEntity<?> requestEntity = 
                new HttpEntity< MultiValueMap<String, String> >(postParams, getHeaders());
        RestTemplate restTemplate = new RestTemplate();
        List< HttpMessageConverter<?> > messageConverters = new ArrayList< HttpMessageConverter<?> >();

        messageConverters.add( new MappingJacksonHttpMessageConverter() );
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        restTemplate.setMessageConverters( messageConverters );

        System.out.println( requestEntity.toString() );
        ResponseEntity result = 
                restTemplate.exchange( URL, method, requestEntity, APIResponse.class ) ;
        return result.getBody();
    }

1条回答
贼婆χ
2楼-- · 2019-07-16 13:53

This is not a good way of setting message converters:

List< HttpMessageConverter<?> > messageConverters = new ArrayList< HttpMessageConverter<?> >();   
// empty list created

messageConverters.add( new MappingJacksonHttpMessageConverter() );   
// list has 1 elem now

restTemplate.getMessageConverters().add(new StringHttpMessageConverter());  
// adds StringHttpMessageConverter to restTemplate converter list

restTemplate.setMessageConverters( messageConverters );
// replaces restTemplate converter list with your custom list containing MappingJacksonHttpMessageConverter only
// original list containing StringHttpMessageConverter is LOST

You should rather use consistent approach to this:

List< HttpMessageConverter<?> > messageConverters = new ArrayList< HttpMessageConverter<?> >();   
// empty list created

messageConverters.add( new MappingJacksonHttpMessageConverter() );      
messageConverters.add( new StringHttpMessageConverter() );  

restTemplate.setMessageConverters( messageConverters );
查看更多
登录 后发表回答