【问题标题】:how to post body x-www-form-urlencoded using webclient?如何使用 webclient 发布正文 x-www-form-urlencoded?
【发布时间】:2021-03-14 02:56:30
【问题描述】:
    MultiValueMap<String, String> body_data = new LinkedMultiValueMap();
    body_data.add("param1", {param1});
    ...
    WebClient webClient = WebClient.builder().baseUrl(api_url+request_url)
            .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
            .build();

    String result = webClient.post().contentType(MediaType.APPLICATION_FORM_URLENCODED)
                    .bodyValue(BodyInserters.fromFormData(body_data)).retrieve().bodyToMono(String.class).block();

然后它返回

org.springframework.web.reactive.function.client.WebClientRequestException: Content type 'application/x-www-form-urlencoded' not supported for bodyType=org.springframework.web.reactive.function.BodyInserters$DefaultFormInserter; nested exception is org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/x-www-form-urlencoded' not supported for bodyType=org.springframework.web.reactive.function.BodyInserters$DefaultFormInserter

对此有什么建议吗? content-type 应该是 application/x-www-form-urlencoded。

【问题讨论】:

    标签: java spring webclient


    【解决方案1】:
        We can use BodyInserters.fromFormData for this purpose
        
        webClient client = WebClient.builder()
                .baseUrl("SOME-BASE-URL")
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                .build();
        
        return client.post()
                .uri("SOME-URI)
                .body(BodyInserters.fromFormData("username", "SOME-USERNAME")
                        .with("password", "SONE-PASSWORD"))
                        .retrieve()
                        .bodyToFlux(SomeClass.class)
                        .onErrorMap(e -> new MyException("messahe",e))
                .blockLast();
    
    
    In another form:
    
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", "XXXX");
    formData.add("password", "XXXX");
    
    String response = WebClient.create()
        .post()
        .uri("URL")
        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
        .body(BodyInserters.fromFormData(formData))
        .exchange()
        .block()
        .bodyToMono(String.class)
        .block();
    

    【讨论】:

      猜你喜欢
      • 2017-03-27
      • 2020-08-12
      • 1970-01-01
      • 2018-12-25
      • 2017-02-13
      相关资源
      最近更新 更多