使用基本身份验证下载未知文件并补偿重定向

时间:2011-01-23 03:52:53

标签: .net powershell download httpwebrequest

真的?简单地下载文件就不是那么多代码了。基本身份验证和重定向看起来很简单。在我完成这段代码之后,我坐下来认为必须有一个更简单的方法,我正在忽略。我认为这个代码甚至存在问题(不补偿所有成功的状态代码,在头解析等方面不健全)。

编辑:我需要知道Web服务器提供的文件名,以便在本地保存为同名。

我是否真的必须继续向此解决方案添加代码,还是我忽略了一种更简单的方法?

Function DownloadFile ([String]$Source, [String]$Destination, [String]$Domain = $Null, [String]$User = $Null, [String]$Password = $Null)
{
    $Request = [System.Net.WebRequest]::Create($Source)

    If ($User)
    {
        $Credential = New-Object System.Net.NetworkCredential($User, $Password, $Domain)

        $CCache = New-Object System.Net.CredentialCache
        $CCache.Add($Request.RequestURI, "Basic", $Credential)

        $Request.Credentials = $CCache
    }

    $Request.AllowAutoRedirect = $False
    $Response = $Request.GetResponse()
    Switch ([Int]$Response.StatusCode)
    {

        302
        {
            If ($Response.Headers['Content-Disposition'])
            {
                #attachment; filename=something.ext
                $FileName = $Response.Headers['Content-Disposition'].Split('=')[-1]
            }
            Else
            {
                #/foo/bar/something.ext
                $FileName = $Response.Headers['Location'].Split('/')[-1]
            }

            $Response.Close()
            $Location = New-Object System.URI($Request.RequestURI, $Response.Headers['Location'])
            DownloadFile ($Location) ($Destination + '\' + $FileName) $Domain $User $Password
        }

        200
        {
            $ResponseStream = $Response.GetResponseStream()
            $FileStream = New-Object System.IO.FileStream($Destination, [System.IO.FileMode]::Create)
            $Buffer = New-Object Byte[] 1024
            Do
            {
                $ReadLength = $ResponseStream.Read($Buffer, 0, 1024)
                $FileStream.Write($Buffer, 0, $ReadLength)
            } While ($ReadLength -ne 0)
            $FileStream.Close()
        }

        Default
        {
            $Response.Close()
            Throw "Unexpected HTTP Status Code $([Int]$Response.StatusCode)"
        }

    }

    $Response.Close()

}

1 个答案:

答案 0 :(得分:0)

我使用此功能下载文件:

function download-file {
  param([string]$url, [string]$filePath, [string]$user, [string]$pass)
  if ($url -notmatch '^http://') {
    $url = "http://$url"
    write-host "Url corrected to $url"
  }
  $w = New-Object net.webclient
  if ($user) {
    write-debug "setting credentials, user name:  $user"
    $w.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
  }
  $w.DownloadFile($url, $filePath)
}

下载文件并将其存储到路径$filePath。示例:

download-file 'http://www.gravatar.com/avatar/c3ba8d5e440f00f11c7df365a19342b4?s=32&d=identicon&r=PG' c:\tempfile.jpg
ii c:\tempfile.jpg

它应该处理重定向,但在发生任何意外错误时抛出异常。