如何在不使用 Invoke-WebRequest 的情况下在 Powershell 中 POST .json 文件?

2024-05-13

我目前正在做的事情:

Invoke-WebRequest -Uri https://coolWebsite.com/ext/ext -ContentType application/json -Method POST -Body $someJSONFile

我正在寻找一种方法在 Powershell 中发布相同的 .json 文件不使用 Invoke-WebRequest, 如果可能。这种新方法最好允许我获取服务器输出内容并在 powershell 中解析它。

也许通过调用外部 cURL 方法?我真的不确定,我所有的互联网研究都没有结果。

在没有 Invoke-WebRequest 的情况下如何实现上述结果?


你可以试试这个:

# RestRequest.ps1

Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization, System.Web.Extensions

$utf8 = [System.Text.Encoding]::UTF8

function Request-Rest
{
  [CmdletBinding()]
  PARAM (
         [Parameter(Mandatory=$true)]
         [String] $URL,

         [Parameter(Mandatory=$false)]
         [System.Net.NetworkCredential] $credentials,

         [Parameter(Mandatory=$true)]
         [String] $JSON)

  # Remove NewLine from json
  $JSON = $JSON -replace "$([Environment]::NewLine) *",""  

  # Create a URL instance since the HttpWebRequest.Create Method will escape the URL by default.   
  # $URL = Fix-Url $Url
  $URI = New-Object System.Uri($URL,$true)   

  try
  {
    # Create a request object using the URI   
    $request = [System.Net.HttpWebRequest]::Create($URI)   
    # Build up a nice User Agent   
    $UserAgent = "My user Agent"
    $request.UserAgent = $("{0} (PowerShell {1}; .NET CLR {2}; {3})" -f $UserAgent, $(if($Host.Version){$Host.Version}else{"1.0"}),  
                           [Environment]::Version,  
                           [Environment]::OSVersion.ToString().Replace("Microsoft Windows ", "Win"))

    $request.Credentials = $credentials
    $request.KeepAlive = $true
    $request.Pipelined = $true
    $request.AllowAutoRedirect = $false
    $request.Method = "POST"
    $request.ContentType = "application/json"
    $request.Accept = "application/json"

    $utf8Bytes = [System.Text.Encoding]::UTF8.GetBytes($JSON)
    $request.ContentLength = $utf8Bytes.Length
    $postStream = $request.GetRequestStream()
    $postStream.Write($utf8Bytes, 0, $utf8Bytes.Length)
    #Write-String -stream $postStream -string $JSON
    $postStream.Dispose()

    try
    {
      #[System.Net.HttpWebResponse] $response = [System.Net.HttpWebResponse] $request.GetResponse()
      $response = $request.GetResponse()
    }
    catch
    {
      $response = $Error[0].Exception.InnerException.Response; 
      Throw "Exception occurred in $($MyInvocation.MyCommand): `n$($_.Exception.Message)"
    }

    $reader = [IO.StreamReader] $response.GetResponseStream()  
    $output = $reader.ReadToEnd()  

    $reader.Close()  
    $response.Close()
    Write-Output $output  
  }
  catch
  {
    $output = @"
    {
      "error":1,
      "error_desc":"Error : Problème d'accès au serveur $($_.Exception.Message)"
    }
"@    
    Write-Output $output
  }
}

编辑于 2015 年 10 月 19 日

这是一个用法示例:

#$urlBase = "http://192.168.1.1:8080/" 

#######################################################################
#                           Login                                     #
#######################################################################
$wsLogin = "production/login"
Function login
{
  [CmdletBinding()]
  PARAM
  (
    [ValidateNotNullOrEmpty()]
    [String] $login,
    [String] $passwd
  )

  Write-Verbose $wsLogin 
  #$jsonIn = [PSCustomObject]@{"login"=$login;"passwd"=$passwd} | ConvertTo-Json
  $jsonIn = @"
  {
    "login":"$login",
    "passwd":"$passwd"
  }
"@
  Write-Verbose $jsonIn
  $jsonOut = Request-Rest -URL "$urlBase$wsLogin" -JSON $jsonIn -credentials $null
  Write-Verbose $jsonOut
  #return $jsonOut | ConvertFrom-Json 
  return $jsonOut
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在不使用 Invoke-WebRequest 的情况下在 Powershell 中 POST .json 文件? 的相关文章

随机推荐