Use WebClient to POST query and download file

霸气de小男生 提交于 2021-01-27 20:20:57

问题


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?


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!