RestTemplate 踩坑

1⃣️初次使用RestTemplate的post方法时,一直报错500。
原因:headers里没有加Content-Type
解决:设置
request.setHeader(“Content-Type”, “application/x-www-form-urlencoded”);

2⃣️接口收不到post的参数。
原因:设置参数的对象不对。
解决:使用LinkedMultiValueMap

LinkedMultiValueMap params = new LinkedMultiValueMap<>();
params.add("userName", “myname”);
ResponseEntity restfulResult = restTemplate.postForEntity(“/url/itfs”, params, Map.class);

3⃣️获取RestTemplate对象

public class CustomRestTemplateCustomizer implements RestTemplateCustomizer {
    @Override
    public void customize(RestTemplate restTemplate) {
        HttpHost proxy = new HttpHost(127.0.0.1, 8080);
        HttpClient httpClient = HttpClientBuilder.create()
                .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {
                    @Override
                    public HttpHost determineProxy(HttpHost target,
                                                   HttpRequest request,
                                                   HttpContext context)
                            throws HttpException {
                        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
                        return super.determineProxy(target, request, context);
                    }
                }).build();
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
    }
}

@Configuration
@ComponentScan(basePackages = {"com.demo.*"})
public class SpringConfig {
    @Bean
    @Qualifier("customRestTemplateCustomizer")
    public CustomRestTemplateCustomizer customRestTemplateCustomizer() {
        return new CustomRestTemplateCustomizer();
    }
    @Bean
    @DependsOn(value = {"customRestTemplateCustomizer"})
    public RestTemplateBuilder restTemplateBuilder() {
        return new RestTemplateBuilder(customRestTemplateCustomizer()).rootUri("http://127.0.0.1:8080");
    }
    @Bean
    public RestTemplate restTemplate() {
        return restTemplateBuilder().build();
    }
}

你可能感兴趣的:(springmvc)