WebRequest WebResponse を使ってHTTPのデータ送信&受信

URLや送信データは適当に置き換えたもの。

cls

[string]$url = "https://www.google.co.jp/"
[string]$dir = (Split-Path ($MyInvocation.MyCommand.Path) -Parent)
[string]$postext = (Get-Content (Join-Path $dir "postdata.txt"))

#SSL/TSLの設定
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

# HTTP リクエストオブジェクト
$req = [System.Net.WebRequest]::Create($url) -as [System.Net.HttpWebRequest]

# HTTP通信の設定
$req.Method = "POST"
$req.ContentType = "text/xml"

# 送信
$data = [System.Text.Encoding]::Default.GetBytes($postext)
if (0 -lt $data.Length)
{
    $req.ContentLength = $data.Length
    try
    {
        $sw = $req.GetRequestStream()
        $sw.Write($data, 0, $data.Length)
    }
    catch [Exception]
    {
        echo "送信時例外エラー"
    $_.Exception.ToString()
    }
    finally
    {
        if(-not($sw -eq $null)) { $sw.Dispose() }
    }
}
# 受信
try
{
    $res = $req.GetResponse()
    $ress = $res.GetResponseStream()
    $sr = New-Object System.IO.StreamReader($ress)
    $text = $sr.ReadToEnd()
}
catch [Exception]
{
    echo "受信時例外エラー"
    $_.Exception.ToString()
}
finally
{
    if(-not($sr -eq $null)) { $sr.Dispose() }
    if(-not($ress -eq $null)) { $ress.Dispose() }
}

#出力
$text
      • -