Spring RestTemplate如何在application / x-www-form-urlencoded中使用POJO?

时间:2019-05-12 21:50:04

标签: java spring spring-boot resttemplate

当我尝试将POJO与MediaType.APPLICATION_FORM_URLENCODED一起使用

printCont(myclass.getVector())

我得到:

    ExampleRequest exampleRequest = exampleRequest();
    exampleRequest.setId("id");
    exampleRequest.setName("name");

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    HttpEntity<ExampleRequest> exampleRequestEntity = new HttpEntity<>(exampleRequest, headers);

    restTemplate.postForObject(url, exampleRequestEntity, String.class)

是否可以通过org.springframework.web.client.RestClientException: No HttpMessageConverter for [ExampleRequest] and content type [application/x-www-form-urlencoded] 而不是application/x-www-form-urlencoded使用POJO?

2 个答案:

答案 0 :(得分:0)

FormHttpMessageConverter可能丢失。您是否尝试过手动添加?

@SpringBootApplication
public class App extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(App.class);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FormHttpMessageConverter converter = new FormHttpMessageConverter();
        MediaType mediaType = new MediaType("application","x-www-form-urlencoded", Charset.forName("UTF-8"));
        converter.setSupportedMediaTypes(Arrays.asList(mediaType));
        converters.add(converter);
        super.configureMessageConverters(converters);
    }
}

(与弹簧靴有关)

答案 1 :(得分:0)

可以使用FormHttpMessageConverter,它能够将数据与MultiValueMap<String, String>媒体类型所需的application/x-www-form-urlencoded进行数据转换。将以下配置添加到实现WebMvcConfigurer的类中。

@Bean
public FormHttpMessageConverter formHttpMessageConverter() {

    MediaType mediaType = new MediaType("application", "x-www-form-urlencoded", 
        Charset.forName("UTF-8"))

    FormHttpMessageConverter formHttpMessageConverter= new FormHttpMessageConverter();
    formHttpMessageConverter.setSupportedMediaTypes(Collections.singletonList(mediaType));
    return formHttpMessageConverter;
}

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
     converters.add(formHttpMessageConverter());
     super.configureMessageConverters(converters);
}