使用SpringBoot的RestTemplate发送post请求时参数带不上

项目中遇到一个向三方发起请求的数据,不过量不大,就几个方法而已,所以为了方便,我直接用了RestTemplate。

1、配置

@Configuration
public class RestTemplateConfig {
     
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
     
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
     
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }
}

2、发起请求
在你需要的地方使用它!

@Autowired
private RestTemplate restTemplate;

大概的方法有这么些
使用SpringBoot的RestTemplate发送post请求时参数带不上_第1张图片

3、post请求的问题
按照上述API的详解,我做了一个post的提交,代码如下:

 Map<String, String> param = new HashMap<>(2);
 param.put("appKey", Constants.APPKET);
 param.put("appSecret", Constants.SECRET);
 accessToken = restTemplate.postForObject("http://xxxxxx", param, AccessToken.class);

然后,服务器的反馈是…参数为空或格式不正确

改成下面这种就好了。

MultiValueMap<String, String> param = new LinkedMultiValueMap<>(2);
param.add("appKey", Constants.APPKET);
param.add("appSecret", Constants.SECRET);
accessToken = restTemplate.postForObject("http://xxxxxx", param, AccessToken.class);

你可能感兴趣的:(Java,java,post,spring,boot)