问题
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 aNameValueCollection
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?
回答1:
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.
来源:https://stackoverflow.com/questions/39010572/use-webclient-to-post-query-and-download-file