使用 WebClient POST 查询和下载文件 [英] Use WebClient to POST query and download file
问题描述
我可以在单个 WebClient
请求中将数据发布到 URI 并下载文件吗?
Can I post data to a URI and download a file in a single WebClient
request?
TL;DR
我正在使用扩展 WebClient
的类来联系我们的 PHP API 并下载文件.该类将 CookieContainer
添加到 WebClient
以启用 PHP 会话.
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()
向服务器发布一个NameValueCollection
查询以验证以下请求.WebClient.DownloadFile()
下载文件.
WebClient.UploadValues()
posts aNameValueCollection
query to the server to authenticate the following request.WebClient.DownloadFile()
downloads the file.
这是 API 中唯一不是很 RESTful 的部分,我更愿意将其移动到单个无状态查询中.
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.
我可以在调用 DownloadFile()
之前使用 WebClient.QueryString
手动设置 NameValueCollection
查询字符串,但该方法使用 GET 方法,并且 API 需要 POST 数据.
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.
可以在调用 DownloadFile()
之前将方法设置为 POST 吗?还有别的方法吗?
Can the method be set to POST before calling DownloadFile()
? Is there another way?
推荐答案
答案比我想象的要简单 (doh).
The answer was simpler than I realized (doh).
using (WebClient client = new WebClient())
{
byte[] result = client.UploadValues(url, data);
File.WriteAllBytes(path, result);
}
UploadValues()
发送 POST 数据.返回的 byte[] 数组将是文件.
UploadValues()
sends POST data. The returned byte[] array will be the file.
这篇关于使用 WebClient POST 查询和下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!