簡體   English   中英

如何使用 webclient 發布正文 x-www-form-urlencoded?

[英]how to post body x-www-form-urlencoded using webclient?

    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

對此有何建議? 內容類型應該是 application/x-www-form-urlencoded。

    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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM