Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use WebClient to POST query and download file

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.

  1. WebClient.UploadValues() posts a NameValueCollection query to the server to authenticate the following request.
  2. 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?

like image 320
khargoosh Avatar asked Sep 07 '25 23:09

khargoosh


1 Answers

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.

like image 79
khargoosh Avatar answered Sep 09 '25 18:09

khargoosh