¿Cómo establecer una cadena grande dentro de HttpContent cuando se usa HttpClient?


Entonces, creé un HttpClient y estoy publicando datos usando HttpClient.PostAsync().

Establezco el HttpContent usando

HttpContent content = new FormUrlEncodedContent(post_parameters); donde post_parameters es una lista de pares de valores List<KeyValuePair<string, string>>

El problema es que cuando el HttpContent tiene un valor grande (una imagen convertida a base64 para ser transmitida) obtengo una URL es un error demasiado largo. Eso tiene sentido-causa la url no puede ir más allá de 32.000 caracteres. Pero ¿cómo agrego los datos en el HttpContent si no de esta manera?

Por favor ayuda.

Author: Chains, 2014-05-17

3 answers

Lo descubrí con la ayuda de mi amigo. Lo que te gustaría hacer es evitar usar FormUrlEncodedContent (), porque tiene restricciones en el tamaño del uri. En su lugar, puede hacer lo siguiente :

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

Aquí, no necesitamos usar HttpContent para publicar en el servidor, StringContent hace el trabajo !

 43
Author: Muraad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-23 17:36:17

FormUrlEncodedContent internamente usa Uri.EscapeDataString : a partir de la reflexión, puedo ver que este método tiene constantes que limitan el tamaño de la longitud de la solicitud.

Una posible solución es crear una nueva implementación de FormUrlEncodedContent utilizando System.Net.WebUtility.UrlEncode (. net 4.5) para eludir esta limitación.

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

Para enviar contenido grande, es mejor usar StreamContent.

 25
Author: Cybermaxs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:43

Este código funciona para mí, básicamente envías datos post "application / x-www-form-urlencoded" dentro del contenido de cadena sobre el cliente http, espero que esto pueda ayudar a cualquier persona con el mismo problema como yo

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();
    }
 2
Author: Chris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-17 18:19:46