http requests with powershell

三世轮回 提交于 2019-11-29 03:16:44

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.

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

manojlds

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

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.

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

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

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