使用HttpClient时如何在HttpContent中设置大字符串?

所以,我创建了一个HttpClient并使用HttpClient.PostAsync()发布数据。

我使用了HttpContent

HttpContent content = new FormUrlEncodedContent(post_parameters) ; 其中post_parameters是键值对List<KeyValuePair>

问题是,当HttpContent有一个很大的值(一个图像转换为base64要传输)我得到一个URL太长的错误。 这是有道理的 – 因为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 :从reflection中,我可以看到此方法具有限制请求长度大小的常量。

一种可能的解决方案是使用System.Net.WebUtility.UrlEncode (.net 4.5)创建FormUrlEncodedContent的新实现来绕过此限制。

 public class MyFormUrlEncodedContent : ByteArrayContent { public MyFormUrlEncodedContent(IEnumerable> nameValueCollection) : base(MyFormUrlEncodedContent.GetContentByteArray(nameValueCollection)) { base.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); } private static byte[] GetContentByteArray(IEnumerable> nameValueCollection) { if (nameValueCollection == null) { throw new ArgumentNullException("nameValueCollection"); } StringBuilder stringBuilder = new StringBuilder(); foreach (KeyValuePair 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客户端在字符串内容中发送post数据“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(); }