Wednesday, May 22, 2019

Listening for HTTP requests in PowerShell

I recently needed to test that an application made a reasonable HTTP request, so I wanted a convenient way to listen for requests and see the contents. It turns out the .NET Framework has an HttpListener class, so PowerShell can do the job. This sets up a listener on port 8080, waits for a connection, and prints the body:

$listener = [System.Net.HttpListener]::new()
$listener.Prefixes.Add('http://localhost:8080/')
$listener.Start()
$ctx = $listener.GetContext() # waits for connection
[System.IO.StreamReader]::new($ctx.Request.InputStream).ReadToEnd()
$listener.Close()

No comments:

Post a Comment