【问题标题】:Spring WebClient equivalent of Http request.setEntity()?Spring WebClient 相当于 Http request.setEntity()?
【发布时间】:2021-11-07 07:13:33
【问题描述】:

我目前正在尝试重构旧的 HTTP 代码以使用 Spring boot WebClient。

我有这个用于 POST 方法的旧代码:

HttpPost request = new HttpPost(url);

request.addHeader(AUTHORIZATION, token);

request.addHeader("Accept", "*/*");

List<NameValuePair> nameValuePairs = new ArrayList<>();

nameValuePairs.add(new BasicNameValuePair("grant_type", grantType));

nameValuePairs.add(new BasicNameValuePair("scope", DEFAULT));

request.setEntity(new UrlEncodedFormEntity(nameValuePairs));

我想知道是否有办法在 WebClient 中执行类似于 setEntity 的操作?这是我到目前为止所拥有的..

MultiValueMap<String, String> bodyValues = new LinkedMultiValueMap<>();

bodyValues.add("grant_type", grantType);

bodyValues.add("scope", DEFAULT);

WebClient webClient = WebClient.create();

String resp = webClient.post().uri(new URI(url))

            .header(AUTHORIZATION, token)

            .header("Content-Type", "application/x-www-form-urlencoded")

            .header("Accept", "*/*")

            .body(BodyInserters.fromFormData(bodyValues))

            .retrieve()

            .bodyToMono(String.class)

            .block();

但是将多值映射添加到正文中不起作用。如果有人对此有所了解,将不胜感激!谢谢

【问题讨论】:

  • “将多值映射添加到正文不起作用”是什么意思?你有例外吗?没有例外,但请求正文中没有任何内容?

标签: java spring spring-boot spring-webflux


【解决方案1】:

您是否尝试过以下方法?

String resp = webClient.post().uri(new URI(url))
            .header(AUTHORIZATION, token)
            .header("Content-Type", "application/x-www-form-urlencoded")
            .header("Accept", "*/*")
            .body(BodyInserters.fromFormData("grant_type", grantType).with("scope", DEFAULT))
            .retrieve()
            .bodyToMono(String.class)
            .block();

【讨论】:

    猜你喜欢
    • 2014-03-19
    • 2021-10-26
    • 2021-04-03
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 2019-06-14
    • 1970-01-01
    相关资源
    最近更新 更多