JSON example

{
    "Computername": "abc",
    "Postype": "ABCDE"
}

Invoke-WebRequest

# Using Invoke-WebRequest to make a GET request
$response = Invoke-WebRequest -Uri 'http://localhost:8080/GetName?macadress=aabbccddeeffgg' -Method Get

# Display the type of object returned
Write-Host "Response type:" $response.GetType().FullName

# Accessing raw content and manually parsing JSON
$jsonData = $response.Content | ConvertFrom-Json

# Displaying the parsed data
Write-Host "Computername:" $jsonData.Computername
Write-Host "Postype:" $jsonData.Postype

Output Explanation for Invoke-WebRequest:

  • Response Type: The response is a HtmlWebResponseObject, which is more complex and includes:
    • Content: The raw string of the response body.
    • Headers: All headers returned by the server.
    • StatusCode: HTTP status code of the response.
  • Manual Parsing: Since Invoke-WebRequest returns raw content, you need to manually parse JSON using ConvertFrom-Json

Invoke-RestMethod

# Using Invoke-RestMethod to make a GET request
$response = Invoke-RestMethod -Uri 'http://localhost:8080/GetName?macadress=aabbccddeeffgg' -Method Get

# Display the type of object returned
Write-Host "Response type:" $response.GetType().FullName

# Directly accessing the parsed JSON data
Write-Host "Computername:" $response.Computername
Write-Host "Postype:" $response.Postype

Key Differences:

  1. Response Handling:
    • Invoke-WebRequest: Returns a detailed HtmlWebResponseObject including raw content, headers, and status codes. You need to parse JSON manually.
    • Invoke-RestMethod: Automatically parses the response into a PowerShell object, making it easier to access structured data directly.
  2. Ease of Use:
    • Invoke-WebRequest: Best for scenarios where you need to work with raw HTML, headers, or need detailed control over the HTTP response.
    • Invoke-RestMethod: Ideal for interacting with REST APIs and working with structured data like JSON or XML.
  3. Performance:
    • Invoke-RestMethod is generally faster and more straightforward when dealing with APIs that return structured data, as it skips the need for manual parsing.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.