How to set large string inside HttpContent when using HttpClient?

前端 未结 3 1956

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

I set the HttpContent using

HttpCo

3条回答
  •  庸人自扰
    2020-12-08 07:42

    FormUrlEncodedContent internally uses Uri.EscapeDataString : from reflection, I can see that this method has constants limiting the size of request length.

    A possible solution is to create a new implementation of FormUrlEncodedContent by using System.Net.WebUtility.UrlEncode (.net 4.5) to bypass this limitation.

    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", "+");
        }
    }
    

    To send large content, it's better to use StreamContent.

提交回复
热议问题