从Powershell上的HTTP请求获取响应链接
下面的Powershell脚本对存储在我的硬盘中的图像运行Google搜索 我怎样才能获得链接,然后再进入结果页面?是否可以导航到其上显示的不同网页 我尝试了从Powershell上的HTTP请求获取响应链接,powershell,httprequest,Powershell,Httprequest,下面的Powershell脚本对存储在我的硬盘中的图像运行Google搜索 我怎样才能获得链接,然后再进入结果页面?是否可以导航到其上显示的不同网页 我尝试了$request.Links |选择href尝试获取链接列表,但无效。我还尝试将Write Output$respStream添加到代码中,但它没有运行 Set-ExecutionPolicy Bypass -scope Process -Force function Get-GoogleImageSearchUrl { para
$request.Links |选择href
尝试获取链接列表,但无效。我还尝试将Write Output$respStream
添加到代码中,但它没有运行
Set-ExecutionPolicy Bypass -scope Process -Force
function Get-GoogleImageSearchUrl
{
param(
[Parameter(Mandatory = $true)]
[ValidateScript({ Test-Path $_ })]
[string] $ImagePath
)
# extract the image file name, without path
$fileName = Split-Path $imagePath -Leaf
# the request body has some boilerplate before the raw image bytes (part1) and some after (part2)
# note that $filename is included in part1
$part1 = @"
-----------------------------7dd2db3297c2202
Content-Disposition: form-data; name="encoded_image"; filename="$fileName"
Content-Type: image/jpeg
"@
$part2 = @"
-----------------------------7dd2db3297c2202
Content-Disposition: form-data; name="image_content"
-----------------------------7dd2db3297c2202--
"@
# grab the raw bytes composing the image file
$imageBytes = [Io.File]::ReadAllBytes($imagePath)
# the request body should sandwich the image bytes between the 2 boilerplate blocks
$encoding = New-Object Text.ASCIIEncoding
$data = $encoding.GetBytes($part1) + $imageBytes + $encoding.GetBytes($part2)
# create the HTTP request, populate headers
$request = [Net.HttpWebRequest] ([Net.HttpWebRequest]::Create('http://images.google.com/searchbyimage/upload'))
$request.Method = "POST"
$request.ContentType = 'multipart/form-data; boundary=---------------------------7dd2db3297c2202' # must match the delimiter in the body, above
$request.ContentLength = $data.Length
# don't automatically redirect to the results page, just take the response which points to it
$request.AllowAutoredirect = $false
# populate the request body
$stream = $request.GetRequestStream()
$stream.Write($data, 0, $data.Length)
$stream.Close()
# get response stream, which should contain a 302 redirect to the results page
$respStream = $request.GetResponse().GetResponseStream()
# pluck out the results page link that you would otherwise be redirected to
(New-Object Io.StreamReader $respStream).ReadToEnd() -match 'HREF\="([^"]+)"' | Out-Null
$matches[1]
}
$url = Get-GoogleImageSearchUrl "C:\Users\Path\filename.jpeg"
Start-Process $url
正如@soc所提到的,您不需要流来拉取url,移动到的位置在响应头中:
$request = [Net.HttpWebRequest] ([Net.HttpWebRequest]::Create('http://images.google.com/searchbyimage/upload'))
$request.AllowAutoredirect = $false
...
$response = $request.GetResponse()
if ($response.StatusCode -eq 302) {
$redirect_url = $response.Headers["Location"]
write-host $redirect_url
}
您是否正在尝试获取
302
重定向到的URL?如果是,请阅读响应的位置
标题。为什么要使用[Net.HttpWebRequest]
来发出web请求,而不是使用调用WebRequest
?这不一定能解决你的问题,但可以引导你走向正确的方向