0

我发现了这样做的不同示例,但无法使它们的任何组合起作用。

基本上,我有一个可以从网络链接生成文档的内网系统,并且我知道我要下载哪些文件。我能够生成要下载的链接列表,但是在程序中对系统进行身份验证时遇到了问题。我不断收到 401 错误:

Public Shared Sub DownloadFiles(_tool As Tool)
    Dim links As List(Of String) = GetJiraLinks(_tool)

    Dim downloader As New WebClient

    ' Initialize the client
    Dim reqParm As New Specialized.NameValueCollection

    reqParm.Add("os_username", "user")
    reqParm.Add("os_password", "pass")
    reqParm.Add("os_destination", "/secure/")

    downloader.Credentials = New NetworkCredential("user", "pass")

    Dim uploadLocation As String = My.Settings.jiraLocation & "login.jsp"

    'downloader.Headers.Add("Content-Type", "application/x-www-form-urlencoded")

    Dim responseBytes = downloader.UploadValues(uploadLocation, "POST", reqParm)

    Dim responseBody = (New Text.UTF8Encoding).GetString(responseBytes)

    Dim workingDir As String = CreateWorkingDir()

    For Each link As String In links
        Dim tempUri As New Uri(link)

        Dim localpath As String = workingDir & "\" & System.IO.Path.GetFileName(tempUri.LocalPath)

        downloader.DownloadFile(tempUri, localpath)
    Next
End Sub
4

1 回答 1

1

我想我会发布一个完整的解决方案示例。许多其他帖子链接到可识别 cookie 的 Web 客户端(如何让 WebClient 使用 Cookie?),但无法实际显示。这是我的:

Public Shared Sub DownloadFiles(_tool As Tool)
    Dim links As List(Of String) = GetJiraLinks(_tool)

    Dim downloader As New CookieAwareWebClient

    ' Start by requesting the page.

    Dim loginPage As String = My.Settings.jiraLocation & "login.jsp"

    ' Initialize the client
    Dim reqParm As New Specialized.NameValueCollection

    reqParm.Add("os_username", "user")
    reqParm.Add("os_password", "pass")
    reqParm.Add("os_destination", "/secure/")

    Dim responseBytes = downloader.UploadValues(loginPage, "POST", reqParm)

    Dim responseBody = (New Text.UTF8Encoding).GetString(responseBytes)

    Dim workingDir As String = CreateWorkingDir()

    For Each link As String In links
        Dim tempUri As New Uri(link)

        Dim localpath As String = workingDir & "\" & System.IO.Path.GetFileName(tempUri.LocalPath)

        downloader.DownloadFile(tempUri, localpath)
    Next
End Sub
于 2013-05-21T06:30:09.933 回答