http requests with powershell

流过昼夜 提交于 2019-12-18 03:53:59

问题


I am looking to make http requests to web pages with powershell, is this possible and if so, how may I achieve this?

Can I make requests to https pages? I am able to make http requests with a bat file but not https, was hoping I could https page requests with powershell.


回答1:


You can use the usual WebRequest and HttpWebRequest classes provided by the .NET framework.

$request = [System.Net.WebRequest]::Create('http://example.com')
# do something with $request

It's no different from using the same classes and APIs from C#, except for the syntactic differences to PowerShell.

PowerShell v3 also brings Invoke-WebRequest and a few others.




回答2:


Try this:

(New-Object System.Net.WebClient).DownloadString("http://stackoverflow.com")

WebClient.DownloadString Method (String)

or in PowerShell 3.0,

(Invoke-WebRequest http://stackoverflow.com).content

Invoke-WebRequest




回答3:


Depending on what you are doing, you can also use System.Net.WebClient, which is a simplified abstraction of HttpWebRequest

$client = new-object system.net.webclient

Look here for difference: What difference is there between WebClient and HTTPWebRequest classes in .NET?

PS: With Powershell v3.0, you have Invoke-WebRequest and Invoke-RestMethod cmdlets which can be used for similar purposes




回答4:


If all else fails, use Curl from http://curl.haxx.se . You can set everything, including certificate handling, POSTs, etc. Not subtle, but it works and handles all of the odder cases; e.g. you can set the --insecure flag to ignore certificate name issues, expiration, or test status.




回答5:


You can create HTTP, HTTPS, FTP and FILE requests using Invoke-WebRequest cmdlet. This is pretty easy and gives many options to play around. Example: To make simple http/https requests to google.com

Invoke-WebRequest -Uri "http://google.com"

More references can be found MSDN




回答6:


This code works with both ASCII & binary files over https in powershell:

# Add the necessary .NET assembly
Add-Type -AssemblyName System.Net.Http

# Create the HttpClient object
$client = New-Object -TypeName System.Net.Http.Httpclient

# Get the web content.
$task = $client.GetByteArrayAsync("https://stackoverflow.com/questions/7715695/http-requests-with-powershell")

# Wait for the async call to finish
$task.wait();

# Write to file
[io.file]::WriteAllBytes('test.html',$task.result)

Tested on Powershell 5.1.17134.1, Win 10



来源:https://stackoverflow.com/questions/7715695/http-requests-with-powershell

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