PowerShell v3 Invoke-WebRequest: Troubles with forms

前端 未结 4 407
花落未央
花落未央 2021-01-04 04:38

Since I upgraded to Windows 8 a lot of my PowerShell scripts relying on launching an invisible IE won’t quite work anymore, so I tried switching to the Invoke-WebRequest

相关标签:
4条回答
  • 2021-01-04 05:18

    Try doing the post directly e.g.:

    $formFields = @{username='john doe';password='123'}
    Invoke-WebRequest -Uri $myUrl -Method Post -Body $formFields -ContentType "application/x-www-form-urlencoded"
    
    0 讨论(0)
  • 2021-01-04 05:20

    If you're me and have been troubleshooting a bad Web Request, in my case a -Body that was becoming null at my API, then you will want to know about the gotcha that is about interleaving your line continuations with comments. This

    $r = iwr -uri $url `
        -method 'POST' `
        -headers $headers `
        # -contenttype 'application/x-www-form-urlencoded' ` # default
        -Body $body
    

    Notice the commented out line # -contenttype 'application/x-www-form-urlencoded' # default

    Putting a comment truncates the remaining back-ticked line continuation. Therefore, in my case my web request ended up with a request having 0-byte payload.

    0 讨论(0)
  • 2021-01-04 05:22

    To address your problem with the unsigned/untrusted certificate, add the line

    [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
    

    before the Invoke-WebRequest statement

    0 讨论(0)
  • 2021-01-04 05:36

    The example in the question works, but you have to use rb and not $rb in the first line:

    $response = Invoke-WebRequest -Uri $myUrl -Method Default -SessionVariable rb
    

    I also had to use ($myUrl + '/login') since this is my login address.

    $response = Invoke-WebRequest -Uri ($myUrl + '/login') -Method Default -SessionVariable rb

    And in the last line used ($myUrl + $form.Action):

    $response = Invoke-WebRequest -Uri ($myUrl + $form.Action) -WebSession $rb -Method POST
    
    0 讨论(0)
提交回复
热议问题