且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有 Invoke-WebRequest 的情况下在 Powershell 中发布 .json 文件?

更新时间:2022-11-03 10:34:56

你可以试试这个:

# 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
  }
}

于 19-10-2015 编辑


Edited 19-10-2015

这是一个示例用法:

#$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
}