Skip to content

Instantly share code, notes, and snippets.

@0xquad
Created August 16, 2018 20:34
Show Gist options
  • Save 0xquad/feabaab31b449939a350eef5af907971 to your computer and use it in GitHub Desktop.
Save 0xquad/feabaab31b449939a350eef5af907971 to your computer and use it in GitHub Desktop.
JSON API fetch tests with Powershell
function ConvertTo-JSON([object] $item){
add-type -assembly system.web.extensions
$ps_js=new-object system.web.script.serialization.javascriptSerializer
return $ps_js.Serialize($item)
}
function ConvertFrom-JSON([object] $item){
add-type -assembly system.web.extensions
$ps_js=new-object system.web.script.serialization.javascriptSerializer
return , $ps_js.DeserializeObject($item)
}
function Invoke-WebRequest($url, $method, $data, $contenttype) {
$request = [System.Net.WebRequest]::Create($url)
if ($method -eq "POST") {
$request.Method = "POST"
$request.ContentType = (
{$($contenttype)},
{'application/x-www-form-urlencoded'}
)[!$contenttype -eq $null]
$reqstream = $request.GetRequestStream()
$writer = new-object System.IO.StreamWriter($reqstream)
$writer.Write($data)
}
$res = $request.GetResponse()
$stream = $res.GetResponseStream()
$reader = new-object System.IO.StreamReader($stream)
$output = $reader.ReadToEnd()
return $output
}
$r = Invoke-WebRequest 'http://httpbin.org/post' -method 'POST' -data 'test=123'
$json = ConvertFrom-JSON $r
$json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment