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

时间:2014-06-26 17:10:50

标签: powershell

我目前在做什么:

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

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

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

如果没有Invoke-WebRequest,我怎样才能实现上述结果?

2 个答案:

答案 0 :(得分:3)

你可以试试这个:

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

答案 1 :(得分:-1)

很容易将该代码转换为cURL

curl -v --insecure -X POST -H“Content-Type:application / json”--data-binary someJSONFile.js https://coolWebsite.com/ext/ext/