spring web客户端提交Long类型的表单数据

huangapple go评论70阅读模式
英文:

spring web client post form data of Long type

问题

需要通过表单数据将数据发布到REST API。值是长整型的值。我已经编写了下面的代码,但出现了错误。

MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
formData.add("commentId", Long.valueOf(98578976));
formData.add("reactionID", Long.valueOf(609878777));

webClient
    .post()
    .uri(url)
    .contentType(MediaType.APPLICATION_FORM_URLENCODED)
    .header("authorization", accessToken)
    .syncBody(formData)
    .retrieve()
    .bodyToMono(SocialFeed.class)
    .block();

错误:java.lang.ClassCastException: 无法将类java.lang.Long转换为类java.lang.String(java.lang.Long和java.lang.String位于加载程序'bootstrap'的java.base模块中)。

通常,它期望的是字符串字符串的多值映射。如何发布其他类型的数据?键是String,值是long?

(注意:这是您提供的代码翻译,没有其他内容。)

英文:

i need to post data to a rest api through form data.
the values are long values. i have written the below code, its giving the error.

MultiValueMap&lt;String, Object&gt; formData = new LinkedMultiValueMap&lt;&gt;();
  formData.add(&quot;commentId&quot;, Long.valueOf(98578976));
  formData.add(&quot;reactionID&quot;, Long.valueOf(609878777));


         webClient
          .post()
          .uri(url)
          .contentType(MediaType.APPLICATION_FORM_URLENCODED)
          .header(&quot;authorization&quot;, accessToken)
          .syncBody(formData)
          .retrieve()
          .bodyToMono(SocialFeed.class)
          .block();

Error:java.lang.ClassCastException: class java.lang.Long cannot be cast to class java.lang.String (java.lang.Long and java.lang.String are in module java.base of loader 'bootstrap').

generally its excepting multi value map of string, string . how to post other types of data ?
key is String, value is long ?

答案1

得分: 2

你需要将所有数据以String格式放入MultiValueMap中。

MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("commentId", String.valueOf(98578976L));
formData.add("reactionID", String.valueOf(609878777L));

你使用的Web客户端可能会在将数据转换为String类型时出现问题(我认为这是在底层执行的操作)。

对你有利的一点是,你能够通过将你的数据手动转换为String来控制将要被发布的内容。因此,你不必依赖内部的序列化器/转换器等。

英文:

You need to put all data in the String format for a MultiValueMap.

MultiValueMap&lt;String, String&gt; formData = new LinkedMultiValueMap&lt;&gt;();
formData.add(&quot;commentId&quot;, String.valueOf(98578976L));
formData.add(&quot;reactionID&quot;, String.valueOf(609878777L));

The webclient that you use might have issues with casting data to a String type (I believe that what he does under the hood).

What is good for you - that you are able to control what exactly will be posted by casting your data to String manually. So you do not have to rely on internal serializers/casts/etc.

huangapple
  • 本文由 发表于 2020年9月21日 17:37:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63989683.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定