Need help with System.Net.WebRequest in PowerShell

Hey Everyone!

I understand I can use Invoke-WebRequest for what I am doing but I am trying to use this class and build the request. Unfortunately I haven’t had any success to get it to work.

I am trying to invoke a RabbitMQ API call. My code is below.

try {
    $webrequest = [System.Net.WebRequest]::Create("http://RabbitMQ/api/nodes");
    $webrequest.Method = "GET"
    $webrequest.PreAuthenticate = $true
    $webrequest.Headers.Add("Authorization", "Basic " + "dGVzdDp0ZXN0")
    $webrequest.ContentType = "application/json"
    $response = $webrequest.GetResponse()
    $response
}
catch [System.Net.WebException] {
    $Request = $_.Exception
    Write-host "Exception caught: $Request"
}

The error I get back is that the operation timed out. I know the site is running as I can hit the endpoint myself on my browser. Is there something I am doing incorrect?

Gosh I hope that’s not a real password.

WebRequest isn’t a drop-in replacement for a browser. It’s possible the server is looking for something else in the HTTP headers, that you haven’t provided. But you’re also saying it’s a JSON content body, but you’re doing a GET, which doesn’t have a BODY. So it’s possible you’re confusing it. I don’t know enough about RabbitMQ to tell you what it expects.

Hi there Don,

First and most importantly that is not a real password. That is not even the correct URL. I always modify my code before I post it here. I try my best not to paste real endpoints/passwords/etc. :slight_smile: Thank you for pointing that out though.

I can use the Invoke-WebRequest cmdlet and pass in the URL & Password as a PSCredential and Method=GET and everything works fine. However trying to build the request using this class I have to inject the username/password into the header.

I can also run this URL via Fiddler and I pass in the Authorization and Content-Type into the Header and it works. Ill keep digging but thank you for your thoughts. If you have any more, please share them.

-Michael

Update: I got this working.

I ended up using the System.Net.WebClient Class downloadstring() method. I was making a RabbitMQ API Web call to retrieve some data on my Cluster environment. Code snippet below.

$url = 
$client = New-Object System.Net.WebClient;
$client.headers["Authorization"] = "BASIC dGVzdDp0ZXN0"   ### Your password is Base64 Encoded
try
	{
	    $result = $client.DownloadString($url)
            $result
	}
	catch [System.Net.WebException]
	{
	    $result = $_.Exception.Response
            $result
	}