Skip to content

Instantly share code, notes, and snippets.

@nolim1t
Created January 7, 2010 05:29
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nolim1t/271018 to your computer and use it in GitHub Desktop.
Save nolim1t/271018 to your computer and use it in GitHub Desktop.
Sample HTTP Request in Powershell
Powershell HTTP Request
$r = [System.Net.WebRequest]::Create("http://url/")
$resp = $r.GetResponse()
$reqstream = $resp.GetResponseStream()
$sr = new-object System.IO.StreamReader $reqstream
$result = $sr.ReadToEnd()
write-host $result
Username and passwords
$creds = new-object System.Net.NetworkCredential "username", "password"
$uri = mew-object System.Uri "http://url/"
$credcache = new-object System.Net.CredentialCache
$credcache.Add($uri, "Basic", $creds)
$webrequestobject.Credentials = $credcache
@nolim1t
Copy link
Author

nolim1t commented May 4, 2010

One Liner version

Powershell -Command "$r = [System.Net.WebRequest]::Create('http://url/'); $resp = $r.GetResponse(); $respstream = $resp.GetResponseStream(); $sr =
new-object System.IO.StreamReader $respstream; $result = $sr.ReadToEnd(); write
-host $result"

@theznerd
Copy link

theznerd commented Jul 2, 2015

you can combine the getresponse and getresponsestream methods into one line making it:
$sr = new-object System.IO.StreamReader (($r.GetResponse()).GetResponseStream())

EDIT: also, if you want to use default credentials of the running user (for automation via logon script) you can add:
$r.UseDefaultCredentials = $true

after line 3

@nilesh-akhade
Copy link

Shouldnt we close or dispose the response.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment