Can I post data to a URI and download a file in a single WebClient request?
TL;DR
I'm using a class extending WebClient to contact our PHP API and download a file. The class adds a CookieContainer to the WebClient to enable a PHP session.
WebClient.UploadValues() posts a NameValueCollection query to the server to authenticate the following request.WebClient.DownloadFile() downloads the file.This is the only part of the API that's not very RESTful and I'd prefer to move this into a single stateless query.
I can use WebClient.QueryString to manually set the NameValueCollection query string before calling DownloadFile() but that method uses the GET method, and the API is expecting POST data.
Can the method be set to POST before calling DownloadFile() ? Is there another way?
The answer was simpler than I realized (doh).
using (WebClient client = new WebClient())
{
byte[] result = client.UploadValues(url, data);
File.WriteAllBytes(path, result);
}
UploadValues() sends POST data. The returned byte[] array will be the file.
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