How to catch post/get variables with Powershell httpListener? - powershell

I want to know how to catch url vars with powershell system.net.HttpListener
Thanks
$listener = New-Object system.net.HttpListener
$listener.Prefixes.Add('http://127.0.0.1:8080')
$listener.Start()
$context = $listener.GetContext() # block
$request = $context.Request
$response = $context.Response
# $var = read post/get var
$page = Get-Content -Path C:\play.html -Raw
$page = $page.Replace('%VAR%',$var)
$buffer = [System.Text.Encoding]::UTF8.GetBytes($page)
$response.ContentLength64 = $buffer.Length
$output = $response.OutputStream
$output.Write($buffer,0,$buffer.Length)
$output.Close()
$listener.Stop()

If the method header is GET then use the QueryString property to get the query parameters. If the method header is POST then check HasEntityBody property and if that is true, read the POST data from the body using the InputSteam property.

Related

Powershell - How to receive large response-headers from error-response of a web-request?

I am looking for a solution to parse an error-response of a given web-service.
Below sample works great in general, but if the response is larger than 64kb then the content is not availabe in the exception at all.
I have seen some solutions recommending to use webHttpClient and increase the MaxResponseContentBufferSize here, but how can I do this for a given WebClient-object?
Is there any option to change that BufferSize globally for all net-webcalls like below TLS12-settings?
Here is my sample-code:
# using net-webclient to use individual user-side proxy-settings:
$web = new-object Net.WebClient
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$url = "address to web-service"
try {
$response = $web.DownloadString($url)
} catch [System.Net.WebException] {
# this part needs to work even if the error-response in larger than 64kb
# unfortunately the response-object is empty in such case
$message = $_.Exception.Response
$stream = $message.GetResponseStream()
$reader = new-object System.IO.StreamReader ($stream)
$body = $reader.ReadToEnd()
write-host "#error:$body"
}
I solved it at the end by switching to system.net.httpclient.
That way I still repect any custom proxy-settings and also avoid the above mentioned 64kb-limit in any error-response. Here a sample how to use it:
$url = "address to web-service"
$cred = Get-Credential
# define settings for the http-client:
Add-Type -AssemblyName System.Net.Http
$ignoreCerts = [System.Net.Http.HttpClientHandler]::DangerousAcceptAnyServerCertificateValidator
$handler = [System.Net.Http.HttpClientHandler]::new()
$handler.ServerCertificateCustomValidationCallback = $ignoreCerts
$handler.Credentials = $cred
$handler.PreAuthenticate = $true
$client = [System.Net.Http.HttpClient]::new($handler)
$client.Timeout = [System.TimeSpan]::FromSeconds(10)
$result = $client.GetAsync($url).result
$response = $result.Content.ReadAsStringAsync().Result
write-host $response

How to get GET parameter?

I was successfully able to open a port on my computer (using only PowerShell) and know when HTTP requests are done to that port. I came up with this simple code:
$listener = [System.Net.Sockets.TcpListener]5566;
$listener.Start();
while ($true) {
$client = $Listener.AcceptTcpClient();
Write-Host "Connected!";
$client.Close();
}
If I open my browser and type http://localhost:5566 in the PowerShell interface it will show a message that a user got connected.
What I need to do is to get the GET parameters of this HTTP request. For example, if instead I had opened my browser and typed http://localhost:5566/test.html?parameter1=xxx&parameter2=yyy.
How can I grab the GET parameters (parameter1 and parameter2) name and values using my simplified code above?
If you are comfortable using the HttpListener instead of the TcpListener. It's easier to do the job.
Below script will output in a browser
Path is /test.html
parameter2 is equal to yyy
parameter1 is equal to xxx
Quick and dirty script
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add("http://localhost:5566/")
try {
$listener.Start();
while ($true) {
$context = $listener.GetContext()
$request = $context.Request
# Output the request to host
Write-Host $request | fl * | Out-String
# Parse Parameters from url
$rawUrl = $request.RawUrl
$Parameters = #{}
$rawUrl = $rawUrl.Split("?")
$Path = $rawUrl[0]
$rawParameters = $rawUrl[1]
if ($rawParameters) {
$rawParameters = $rawParameters.Split("&")
foreach ($rawParameter in $rawParameters) {
$Parameter = $rawParameter.Split("=")
$Parameters.Add($Parameter[0], $Parameter[1])
}
}
# Create output string (dirty html)
$output = "<html><body><p>"
$output = $output + "Path is $Path" + "<br />"
foreach ($Parameter in $Parameters.GetEnumerator()) {
$output = $output + "$($Parameter.Name) is equal to $($Parameter.Value)" + "<br />"
}
$output = $output + "</p></body></html>"
# Send response
$statusCode = 200
$response = $context.Response
$response.StatusCode = $statusCode
$buffer = [System.Text.Encoding]::UTF8.GetBytes($output)
$response.ContentLength64 = $buffer.Length
$output = $response.OutputStream
$output.Write($buffer,0,$buffer.Length)
$output.Close()
}
} finally {
$listener.Stop()
}
Cheers
Glenn

PowerShell WebRequest POST

In Windows PowerShell 3.0 was introduced Invoke-RestMethod cmdlet.
Invoke-RestMethod cmdlet accepts -Body<Object> parameter for setting the body of the request.
Due to a certain limitations Invoke-RestMethod cmdlet could not be used in our case. From the other hand, an alternative solution described in article InvokeRestMethod for the Rest of Us suits our needs:
$request = [System.Net.WebRequest]::Create($url)
$request.Method="Get"
$response = $request.GetResponse()
$requestStream = $response.GetResponseStream()
$readStream = New-Object System.IO.StreamReader $requestStream
$data=$readStream.ReadToEnd()
if($response.ContentType -match "application/xml") {
$results = [xml]$data
} elseif($response.ContentType -match "application/json") {
$results = $data | ConvertFrom-Json
} else {
try {
$results = [xml]$data
} catch {
$results = $data | ConvertFrom-Json
}
}
$results
But it is intended for a GET method only.
Could you please suggest how to extend this code sample with the ability to send the body of the request using POST method (similar to Body parameter in Invoke-RestMethod)?
First, change the line that updates the HTTP method.
$request.Method= 'POST';
Next, you need to add the message body to the HttpWebRequest object. To do that, you need to grab a reference to the request stream, and then add data to it.
$Body = [byte[]][char[]]'asdf';
$Request = [System.Net.HttpWebRequest]::CreateHttp('http://www.mywebservicethatiwanttoquery.com/');
$Request.Method = 'POST';
$Stream = $Request.GetRequestStream();
$Stream.Write($Body, 0, $Body.Length);
$Request.GetResponse();
NOTE: PowerShell Core edition is now open source on GitHub, and cross-platform on Linux, Mac, and Windows. Any issues with the Invoke-RestMethod cmdlet should be reported on the GitHub issue tracker for this project, so they can be tracked and fixed.
$myID = 666;
#the xml body should begin on column 1 no indentation.
$reqBody = #"
<?xml version="1.0" encoding="UTF-8"?>
<ns1:MyRequest
xmlns:ns1="urn:com:foo:bar:v1"
xmlns:ns2="urn:com:foo:xyz:v1"
<ns2:MyID>$myID</ns2:MyID>
</ns13:MyRequest>
"#
Write-Host $reqBody;
try
{
$endPoint = "http://myhost:80/myUri"
Write-Host ("Querying "+$endPoint)
$wr = [System.Net.HttpWebRequest]::Create($endPoint)
$wr.Method= 'POST';
$wr.ContentType="application/xml";
$Body = [byte[]][char[]]$reqBody;
$wr.Timeout = 10000;
$Stream = $wr.GetRequestStream();
$Stream.Write($Body, 0, $Body.Length);
$Stream.Flush();
$Stream.Close();
$resp = $wr.GetResponse().GetResponseStream()
$sr = New-Object System.IO.StreamReader($resp)
$respTxt = $sr.ReadToEnd()
[System.Xml.XmlDocument] $result = $respTxt
[String] $rs = $result.DocumentElement.OuterXml
Write-Host "$($rs)";
}
catch
{
$errorStatus = "Exception Message: " + $_.Exception.Message;
Write-Host $errorStatus;
}

Powershell httplistener handle more than one request at the same time

I´m using a normal powershell httplistener script.
The script listenes on port 80 and gives an response.
Now I tried to handle more than one request as the same time. The problem is that the second respons has to wait until the first response was finished by the script.
I tried to start an own job for every http-request - but I can´t send a response to the listener from the PS-Job.
Does anyone know, how to handle parallel httprequests in PS?
Here is the Script I´m using:
$url = 'http://localhost/'
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add($url)
$listener.Start()
Write-Host "Listening at $url..."
while ($listener.IsListening)
{
$context = $listener.GetContext()
$requestUrl = $context.Request.Url
$response = $context.Response
Write-Host ''
Write-Host "> $requestUrl"
$localPath = $requestUrl.LocalPath
$route = $routes.Get_Item($requestUrl.LocalPath)
if ($route -eq $null)
{
$response.StatusCode = 404
}
else
{
$content = & $route
$buffer = [System.Text.Encoding]::UTF8.GetBytes($content)
$response.ContentLength64 = $buffer.Length
$response.OutputStream.Write($buffer, 0, $buffer.Length)
}
$response.Close()
$responseStatus = $response.StatusCode
Write-Host "< $responseStatus"
}
What is the right way to handle more than one request at the same time?
Thanks #all!
You can use multiple runspaces (even the runspace pool) within the same PowerShell process. See this blog post for details on how to do that.
Check the $request.url.LocalPath or another one of the url properties depending on how much of context you are looking for.
Provide a different response depending on the request.
$htmlout = "<html><link rel=""stylesheet"" href=""MyStleSheet.css""><body class=""body"" />Hello World</body></html>"
$css = ".body {background-color: white;font-size: 20px;font-family: calibri;}"
while($Listener.IsListening -and $noBreak){
$Context = $listener.GetContext()
$request = $context.request
if($request.url.LocalPath -match '.css')
{
$buffer = [System.Text.Encoding]::utf8.getbytes($css)
}
if($request.url.LocalPath -match '.html')
{
$buffer = [System.Text.Encoding]::utf8.getbytes($htmlout)
}
$response = $context.response
$response.contentlength64 = $buffer.length
$response.OutputStream.Write($buffer,0,$buffer.length)
}

How to post a tweet to twitter using Powershell?

Has anyone used the following code? How do I make it post a tweet? I know I have to use the "$req.Context.RawUri = [Uri]'http://api.twitter.com/version/statuses/update.xml" but I can't get the "$res = [xml][DevDefined.OAuth.Consumer.ConsumerRequestExtensions]::ReadBody($req)" right.
Add-Type -Path C:\OAuthDevDefined\DevDefined.OAuth.dll
$cons = New-Object devdefined.oauth.consumer.oauthconsumercontext
$cons.ConsumerKey = 'key'
$cons.ConsumerSecret = 'key'
$cons.SignatureMethod = [devdefined.oauth.framework.signaturemethod]::HmacSha1
$session = new-object DevDefined.OAuth.Consumer.OAuthSession $cons, $null, $null, $null
$accessToken = new-object DevDefined.OAuth.Framework.TokenBase
$at = import-cliXml C:\temp\myTwitterAccessToken.clixml
$accessToken.ConsumerKey, $accessToken.Realm, $accessToken.Token, $accessToken.TokenSecret = `
$at.ConsumerKey, $at.Realm, $at.Token, $at.TokenSecret
$req = $session.Request($accessToken)
$req.Context.RequestMethod = 'GET'
$req.Context.RawUri = [Uri]'http://api.twitter.com/1/statuses/friends_timeline.xml?count=5'
$res = [xml][DevDefined.OAuth.Consumer.ConsumerRequestExtensions]::ReadBody($req)
$res.statuses.status | % { $_.user.Name }
I use OAuth by DevDefined as well. My function looks like this:
function Post-Twitter {
param(
[Parameter(Mandatory=$true)][string]$url
)
if (!$script:accessToken) {
throw 'token is not initialized'
}
try {
$cons = New-Object devdefined.oauth.consumer.oauthconsumercontext
$cons.ConsumerKey = $consumerKey
$cons.ConsumerSecret = $consumerSecret
$cons.SignatureMethod = [devdefined.oauth.framework.signaturemethod]::HmacSha1
$session = new-object DevDefined.OAuth.Consumer.OAuthSession `
$cons,
"http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/authorize",
"http://twitter.com/oauth/access_token"
$token = Get-AccessToken
$req = $session.Request($token)
$req.Context.RequestMethod = 'POST'
$req.Context.RawUri = new-object Uri $url
[DevDefined.OAuth.Consumer.ConsumerRequestExtensions]::ReadBody($req)
} catch {
Write-Warning "Exception: $_"
$null
}
}
Then for simplicity I pass status in query string:
add-type -assembly System.Web
$status = [system.Web.Httputility]::UrlEncode('some tweet')
Post-Twitter "http://api.twitter.com/1/statuses/update.xml?status=$status"
It seems that you know about the consumer key/secret and the token thing, so I'll leave it without further explanation.
I’ve just posted a Powershell Twitter REST API 1.1 Module on TechNet Gallery… You'll be able to post/get from Twitter API! https://goo.gl/s7pmmA