gpt4 book ai didi

java - Spring REST 模板发布

转载 作者:行者123 更新时间:2023-11-30 09:14:22 25 4
gpt4 key购买 nike

我正在使用 Spring 框架并尝试执行发布请求。我的 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 );

关于java - Spring REST 模板发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20557326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com