FormUrlEncodedContent
内部使用Uri.EscapeDataString
:从反射中,我可以看到该方法具有限制请求长度大小的常量。
一个可能的解决方案是FormUrlEncodedContent
通过使用System.Net.WebUtility.UrlEncode
(.net 4.5)创建一个新的实现来绕过这个限制。
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。