VB.NET console application - login to website and download file

落花浮王杯 提交于 2021-02-11 16:54:16

问题


I am working an a VB.NET console application which automatically downloads textfiles from different websites. So far I've been using

My.Computer.Network.DownloadFile(url, local_path, username, password)

and it works fine - but there is one website which uses cookies. Under normal circumstances I have to manually visit the website in my browser, login by entering my credentials into a login form, press the "Log in" button and then there is a link which lets me download the file. If I use this link in my normal download function, I always receive a message "Not logged in." so this is basically my problem: I need to call this URL with a WebClient or HttpWebRequest and log in using my credentials before I tell it to download the file.

However, I can not find a good example or guideline anywhere for this problem. So far, I've tried the following:

Dim client As New WebClient
Dim values As New NameValueCollection()
values.Add("login[username]", "<my_login>")
values.Add("login[password]", "<my_password>")
client.UploadValues("https://www.website.com/customer/account/login/", values)
Dim strDL As String = client.DownloadString("https://www.website.com/downloadFile.php/")
Console.WriteLine(strDL)

This isn't working and my console just puts out "Not logged in."

I know that you can also work with a CookieContainer but not with WebClient, only with HttpWebRequest. I guess I didn't grasp the concept of that yet. In my case, the cookies for the website expire after 1 hour so I assume that my approach with the NameValueCollection also would not work (or maybe it would but only as long as the cookie is valid) so my guess is that I have to somehow log into the website, get the cookie names and values and then use those information to download the file. However, as I said, I can not find a good example on how to do this anywhere.

来源:https://stackoverflow.com/questions/65718094/vb-net-console-application-login-to-website-and-download-file

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