使用 HttpClient 时如何在 HttpContent 中设置大字符串? [英] How to set large string inside HttpContent when using HttpClient?

查看:33
本文介绍了使用 HttpClient 时如何在 HttpContent 中设置大字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我创建了一个 HttpClient 并使用 HttpClient.PostAsync() 发布数据.

So, I created a HttpClient and am posting data using HttpClient.PostAsync().

我使用

HttpContent content = new FormUrlEncodedContent(post_parameters);其中 post_parameters 是键值对的列表 List>

HttpContent content = new FormUrlEncodedContent(post_parameters); where post_parameters is a list of Key value pairs List<KeyValuePair<string, string>>

问题是,当HttpContent 的值很大时(要传输的图像转换为base64),我得到一个URL 太长错误.这是有道理的 - 因为 url 不能超过 32,000 个字符.但是如果不是这样,我如何将数据添加到 HttpContent 中?

Problem is, when the HttpContent has a large value (an image converted to base64 to be transmitted) I get a URL is too long error. That makes sense - cause the url cant go beyond 32,000 characters. But how do I add the data into the HttpContent if not this way?

请帮忙.

推荐答案

我在朋友的帮助下想通了.您想要做的是避免使用 FormUrlEncodedContent(),因为它对 uri 的大小有限制.相反,您可以执行以下操作:

I figured it out with the help of my friend. What you would want to do is avoid using FormUrlEncodedContent(), because it has restrictions on the size of the uri. Instead, you can do the following :

    var jsonString = JsonConvert.SerializeObject(post_parameters);
    var content = new StringContent(jsonString, Encoding.UTF8, "application/json");

在这里,我们不需要使用 HttpContent 来发布到服务器,StringContent 完成了工作!

Here, we don't need to use HttpContent to post to the server, StringContent gets the job done !

这篇关于使用 HttpClient 时如何在 HttpContent 中设置大字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆