[英]Using C# HttpClient, how to POST a string HttpContent to ASP.net Core web API?
[英]How to set large string inside HttpContent when using HttpClient?
所以,我创建了一个HttpClient
并使用HttpClient.PostAsync()
发布数据。
我使用了HttpContent
HttpContent content = new FormUrlEncodedContent(post_parameters)
; 其中post_parameters
是键值对List<KeyValuePair<string, string>>
问题是,当HttpContent
有一个很大的值(一个图像转换为base64要传输)我得到一个URL太长的错误。 这是有道理的 - 因为网址不能超过32,000个字符。 但是,如果不是这样,我如何将数据添加到HttpContent
?
请帮忙。
我在朋友的帮助下想出来了。 你想要做的是避免使用FormUrlEncodedContent(),因为它对uri的大小有限制。 相反,您可以执行以下操作:
var jsonString = JsonConvert.SerializeObject(post_parameters);
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
在这里,我们不需要使用HttpContent发布到服务器,StringContent完成工作!
FormUrlEncodedContent
内部使用Uri.EscapeDataString
:从反射中,我可以看到此方法具有限制请求长度大小的常量。
一种可能的解决方案是使用System.Net.WebUtility.UrlEncode
(.net 4.5)创建FormUrlEncodedContent
的新实现来绕过此限制。
public class MyFormUrlEncodedContent : ByteArrayContent
{
public MyFormUrlEncodedContent(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
: base(MyFormUrlEncodedContent.GetContentByteArray(nameValueCollection))
{
base.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
}
private static byte[] GetContentByteArray(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
{
if (nameValueCollection == null)
{
throw new ArgumentNullException("nameValueCollection");
}
StringBuilder stringBuilder = new StringBuilder();
foreach (KeyValuePair<string, string> current in nameValueCollection)
{
if (stringBuilder.Length > 0)
{
stringBuilder.Append('&');
}
stringBuilder.Append(MyFormUrlEncodedContent.Encode(current.Key));
stringBuilder.Append('=');
stringBuilder.Append(MyFormUrlEncodedContent.Encode(current.Value));
}
return Encoding.Default.GetBytes(stringBuilder.ToString());
}
private static string Encode(string data)
{
if (string.IsNullOrEmpty(data))
{
return string.Empty;
}
return System.Net.WebUtility.UrlEncode(data).Replace("%20", "+");
}
}
要发送大量内容,最好使用StreamContent 。
这段代码对我有用,基本上你在http客户端的字符串内容中发送帖子数据“application / x-www-form-urlencoded”,希望这可以帮助像我一样有问题的人
void sendDocument()
{
string url = "www.mysite.com/page.php";
StringBuilder postData = new StringBuilder();
postData.Append(String.Format("{0}={1}&", HttpUtility.HtmlEncode("prop"), HttpUtility.HtmlEncode("value")));
postData.Append(String.Format("{0}={1}", HttpUtility.HtmlEncode("prop2"), HttpUtility.HtmlEncode("value2")));
StringContent myStringContent = new StringContent(postData.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded");
HttpClient client = new HttpClient();
HttpResponseMessage message = client.PostAsync(url, myStringContent).GetAwaiter().GetResult();
string responseContent = message.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.