SuperDOS
SuperDOS

Reputation: 331

Invoke-Webrequest host variable, Invalid URI: The hostname could not be parsed

I'm trying to do an api call to a webservice and not sure what goes wrong. Could be the quotation that is wrong in the $request variable.

[string]$subKey = "AAAAA-BBBBB-FFFFFF-EEEEEE-DDDDD"
[string]$method = "GET"
[string]$searchParam = "Type"
[string]$searchQuery = "QQ"
$request=("""https://api.test.com/api/assets/search?" + $searchParam + "=" + $searchQuery + "&PageSize=10&Page=1"""+" -Headers @{""Authorization"""+"="""+"SubKey "+$subKey+"""}")

Invoke-WebRequest $request -Method Get

This results in:

Invalid URI: The hostname could not be parsed.

If I just copy the output of $request and run Invoke-WebRequest it works.

Upvotes: 2

Views: 17124

Answers (2)

Julio Cezar Silva
Julio Cezar Silva

Reputation: 2456

For those who may have ended up here due to an issue unrelated to OP's, this may be useful:

Remove quotes from your URL string. Literally:

$url = ($url -replace '"', "")

Specific scenario: trying to get a repo's latest release dynamically, I retrieved URL strings from GitHub API, querying the JSON with jq in PowerShell (an express ticket to Windows Quote Hell) and ended up with quote-inclusive strings.

Upvotes: 3

Martin Brandl
Martin Brandl

Reputation: 58931

The Invoke-WebRequest cmdlet takes an -Uri and a -Headers parameter. Also you can simplify the URL:

[string]$subKey = "AAAAA-BBBBB-FFFFFF-EEEEEE-DDDDD"
[string]$method = "GET"
[string]$searchParam = "Type"
[string]$searchQuery = "QQ"
$uri= "https://api.test.com/api/assets/search?$searchParam=$searchQuery&PageSize=10&Page=1"

Invoke-WebRequest -Uri $uri -Headers @{Authorization ="SubKey $subKey"} -Method Get

Upvotes: 3

Related Questions