Invoke-WebRequest only works at second execution

112 Views Asked by At

I'm working on a script for geting info in a webpage. I've succesfully managed to authenticate and store the info in a WebSession variable and after that, do the rest of the requests.

My problem now is that after encapsulating a request in a function, now it gives me 302 error and the content is the own html code of the page. If I execute the same line of code a 2nd time. It works...

So... a little bit of code:

Function Called:

function Get-ProductCN {
    param (
        [Object]$WebSession,
        [string]$Products
    )
    #Search Internal Code
    $pathPRCode = "/group/canal-online/catalogo-general"
    $queryPRCode = [ordered]@{
    }
    $urlPRCode = New-HttpQueryString -Path $pathPRCode -QueryParameter $queryPRCode

    $payloadPRCode = [ordered]@{
        codODescProducto      = $Products   
        numElementosPorPagina = $Products.Split(" ", [System.StringSplitOptions]::RemoveEmptyEntries).Count
    }
    Write-Host (get-date -format "dd-MM-yyyy HH:mm:ss") "INFO: Function $($MyInvocation.MyCommand) Cookies retrieved: $($WebSession.Cookies.Count)"
    Write-Host (get-date -format "dd-MM-yyyy HH:mm:ss") "INFO: Function $($MyInvocation.MyCommand) URL built for request: $($urlPRCode)"
    Write-Host (get-date -format "dd-MM-yyyy HH:mm:ss") "INFO: Function $($MyInvocation.MyCommand) Payload for request: $($payloadPRCode | ConvertTo-Json -Compress)"

    $responsePrCode = Invoke-WebRequest -Uri $urlPRCode -body $payloadPRCode -Method "GET" -WebSession $WebSession
    $responsePrCode.Content | Out-File "prCode.html"
    try {
        $prCode = $responsePrCode.Content | ConvertFrom-Json -Depth 99 -ErrorAction Stop
    }
    catch {
        Write-Host (get-date -format "dd-MM-yyyy HH:mm:ss") "ERROR: Function $($MyInvocation.MyCommand) - Unable to parse content. Response content is not JSON file."
    }
    return $prCode
}

On the main script. If I execute the function just once and script cannot continue:

$prCode = Get-ProductCN -WebSession $webSession -Products "710663 723345"
Write-Host "Function called Get-ProductCN returned `$prCode=$($prCode.cnProductoConsulta)"

It gives me 302 error and the content is not parsed.

Invoke-WebRequest: C:\Users\IzquieD\Documents\Own Repos\farmabot\bot.ps1:96:23
Line |
  96 |  … nsePrCode = Invoke-WebRequest -Uri $urlPRCode -body $payloadPRCode -M …
     |                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Response status code does not indicate success: 302 (Found).
02-08-2023 13:48:31 ERROR: Function Get-ProductCN - Unable to parse content. Response content is not JSON file.
Function called Get-ProductCN returned $prCode=

Funny thing, If I add same 2 lines again first one fails but second is able to do what its suppose has to do:

 02-08-2023 13:48:31 INFO: Function Get-ProductCN Cookies retrieved: 5
    02-08-2023 13:48:31 INFO: Function Get-ProductCN URL built for request: https://XXXXXXXX:443/group/canal-online/catalogo-general?p_p_lifecycle=2&p_p_state=normal&p_p_resource_id=%2fcatalogues-search-mvc%2fbusqueda%2fproductos%2fcatalogo&p_p_cacheability=cacheLevelPage&p_p_id=cataloguesportlet_WAR_cataloguesportlet&p_p_mode=view
    02-08-2023 13:48:31 INFO: Function Get-ProductCN Payload for request: {"codODescProducto":"710663 723345","numElementosPorPagina":2}
    Function called Get-ProductCN returned $prCode=PR710663 PR723345 

I've tried to add some hard sleep to the Start-Session that gives me the object $WebSession to see if its something related to the speed of the process but nothing...

Any hints? Thanks!

EDIT

A little bit more context after @jdweng feedback.

My whole bot looks like this: Folded functions bot

Start-Session Logs into the webpage with this request and I receive a 302 (Expected):

$responseLogin = Invoke-WebRequest -Uri $urlLogin -Body $loginPayload -Method "POST" -SessionVariable session -MaximumRedirection 0 -SkipHttpErrorCheck 2>$null

The variable "session" is returned and then used in the rest of the process.

First call after Start-Session always fails. Then the rest are fine.

The issue must be in the way I generate the cookies/session object and pass it to the rest of the functions... I guess.

BR

0

There are 0 best solutions below