以编程方式下载文件 [英] Programmatically downloading file
问题描述
我正在尝试使用C#4.5以编程方式登录到第三方网站,然后从该网站的另一个页面下载一个csv文件.我尝试使用以下方法.我没有收到任何错误,但似乎下载了他们登录页面的内容并保存 它是一个csv文件,而不是包含数据的实际csv文件.
Using C# 4.5,I'm trying to programmatically log-on to a third-party website and then download a csv file from another page on that site. I tried using following approach.I dont get any errors but it seems to download the contents of their logon page and save it as a csv file instead of the actual csv file having data.
另外,如果我在登录后阅读了响应流,就会发现我重新获得了登录网页.
Also,if I read the response stream after logging in, I see that I'm getting the log-on webpage back.
我在这里想念什么吗?
What am I missing here please?
另外,我还需要张贴表单的名称.如何实现?请告知.
Plus, I need to post the name of the form as well.How do I achieve that?Please advise.
谢谢.
//Log-on to website and post user and password
var request = new HttpRequestMessage(HttpMethod.Post, myLogonURL);
request.Content = new StringContent("{\"user\":\"abcd\",\"password\":test}", Encoding.UTF8, "application/x-www-form-urlencoded");
var sendTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
var response = sendTask.Result.EnsureSuccessStatusCode();
//Download the file
request = new HttpRequestMessage(HttpMethod.Get, fileDownloadURL);
sendTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response = sendTask.Result.EnsureSuccessStatusCode();
var httpStream = await response.Content.ReadAsStreamAsync();
//Save the downloaded file
using (var fileStream = File.Create(downloadedFilePath))
using (var reader = new StreamReader(httpStream)) {
httpStream.CopyTo(fileStream);
fileStream.Flush();
}
推荐答案
为什么不先看看是否可以使它与curl配合使用,以确保它不是服务器,附带问题?
Why don't you see if you can get it working with something like curl first, to make sure it's not a server-side issue?
很可能是如果没有适当的凭据,服务器将无法提供csv文件,这可能需要登录并维护会话(Cookie等). 冷的请求可能会重定向到登录页面.
It could very well be that the server won't serve the csv file without appropriate credentials, which may require logging in and maintaining a session (cookies, etc.). A cold request is likely to be redirected to a sign in page.
这篇关于以编程方式下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!