我正在使用Spring Framework并尝试执行发布请求。我的post方法采用url,HttpMethod和进入请求正文的参数。
注意:在network.POSTRequest(URL,..,…)中传递的var URL对于每个调用都是不同的。
现在,如果我使用一个像这样的参数调用此方法…(它工作得很漂亮!)
//with one parameter MultiValueMap<String, String> postParams = new LinkedMultiValueMap<String, String>(); postParams.add("id", "524cd432539ed"); network.POSTRequest( URL, HttpMethod.POST, postParams );
,但是如果有两个这样的参数…。(它会引发此错误)
org.springframework.web.client.HttpServerErrorException:500内部服务器错误
//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 );
这是POSTRequest方法
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(); }
这不是设置消息转换器的好方法:
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
您应该对此使用一致的方法:
List< HttpMessageConverter<?> > messageConverters = new ArrayList< HttpMessageConverter<?> >(); // empty list created messageConverters.add( new MappingJacksonHttpMessageConverter() ); messageConverters.add( new StringHttpMessageConverter() ); restTemplate.setMessageConverters( messageConverters );