英文:
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<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();
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<String, String> formData = new LinkedMultiValueMap<>();
formData.add("commentId", String.valueOf(98578976L));
formData.add("reactionID", 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论