I am trying to do a POST like this:
HttpClient hc = new HttpClient();
byte[] bytes = ReadFile(@"my_path");
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("FileName", "001.jpeg"));
postData.Add(new KeyValuePair<string, string>("ConvertToExtension", ".pdf"));
postData.Add(new KeyValuePair<string, string>("Content", Convert.ToBase64String(bytes)));
HttpContent content = new FormUrlEncodedContent(postData);
hc.PostAsync("url", content).ContinueWith((postTask) => {
postTask.Result.EnsureSuccessStatusCode();
});
but I receive this exception:
Invalid URI: The Uri string is too long.
complaining about this line: HttpContent content = new FormUrlEncodedContent(postData);
. For small files it works but I don't understand why for larger ones it doesn't?
When I do POST the content can be larger...Then why it complains about URI?
You should use MultipartFormDataContent ( http://msdn.microsoft.com/en-us/library/system.net.http.multipartformdatacontent%28v=vs.110%29 ) instead of FormUrlEncodedContent, which sends your data as "application/x-www-form-urlencoded".
So even if your using the POST verb, it is still POSTing to a very long url containing your data, hence the error.
The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
See : http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
For a sample, have a look at this answer : ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With