HttpClient:uri字符串太长 [英] HttpClient: The uri string is too long

查看:568
本文介绍了HttpClient:uri字符串太长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过以下尝试将数据发布到生成PDF文件的网络服务中, PDF火箭 太棒了)。

Given the following attempt to post data to a web service that generates PDF files, PDF rocket (which is awesome by the way).

我收到错误消息无效的URI:URI字符串也是如此long

为什么有人会对 POST ed数据施加任意限制?

I get the error Invalid URI: The uri string is too long
Why would anyone impose an arbitrary limit on POSTed data?

using (var client = new HttpClient())
{
    // Build the conversion options
    var options = new Dictionary<string, string>
    {
        { "value", html },
        { "apikey", ConfigurationManager.AppSettings["pdf:key"] },
        { "MarginLeft", "10" },
        { "MarginRight", "10" }
    };

    // THIS LINE RAISES THE EXCEPTION
    var content = new FormUrlEncodedContent(options);

    var response = await client.PostAsync("https://api.html2pdfrocket.com/pdf", content);
    var result = await response.Content.ReadAsByteArrayAsync();
    return result;
}

我收到此多余的错误。

 {System.UriFormatException: Invalid URI: The Uri string is too long.
   at System.UriHelper.EscapeString
   at System.Uri.EscapeDataString
   at System.Net.Http.FormUrlEncodedContent.Encode
   at System.Net.Http.FormUrlEncodedContent.GetContentByteArray

这使我想起 64万就足够了。 ..我的意思是真的吗?

This reminds me of 640k ought to be enough... I mean really?

推荐答案

用帖子可以将内容包含在http消息中URI。 uri的最大长度为2083个字符。您可以在http消息中将其作为JSON而不是URI发送,这是在HttpPost / HttpPut中发送较大数据块的推荐方法。我更改了您的代码以使用它。假设您正在联系的服务可以使用JSON(即开即用的.net Web Api应该没有问题)。

With a post can include the content in the http message instead of the URI. A uri has a max length of 2083 characters. You could send it as JSON in the http message instead of the URI which is the recommended way to send larger chunks of data in an HttpPost/HttpPut. I altered your code to make use of it. This assumes that your service you are contacting can work with JSON (.net Web Api out of the box should have no problem with this).

using (var client = new HttpClient())
{
    // Build the conversion options
    var options = new 
    {
        value = html,
        apikey = ConfigurationManager.AppSettings["pdf:key"],
        MarginLeft = "10",
        MarginRight = "10"
    };

    // Serialize our concrete class into a JSON String
    var stringPayload = JsonConvert.SerializeObject(options);
    var content = new StringContent(stringPayload, Encoding.UTF8, "application/json");

    var response = await client.PostAsync("https://api.html2pdfrocket.com/pdf", content);
    var result = await response.Content.ReadAsByteArrayAsync();
    return result;
}






请务必安装< a href = https://stackoverflow.com/a/18784702/4684797> newtonsoft json 。

这篇关于HttpClient:uri字符串太长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆