4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PowerShellでGETとPOST可能な簡易Webサーバを立てる

Last updated at Posted at 2023-11-01

これはなに?

後述のPowerShellスクリプトで簡易ローカルサーバを立てることができる。
http://127.0.0.1:8080/にGETすると"Hello, world!"を返し、POSTするとBodyの文字列をそのまま返す。
PUTやDELETEには対応せず400 Bad requestを返す。

Ctrl+CやISEの停止ボタンでは止まらないので、停止する時はコンソールそのものを落とすこと。
※類似サイトで「PowerShellを管理者権限で実行すること」と書かれているサイトを見つけたが、手元の環境では通常のadminユーザでも動いた。

スクリプト

my_server.ps1
$url = "http://127.0.0.1:8080/"

$listener = New-Object system.net.HttpListener
$listener.Prefixes.Add($url)
try {
    $listener.Start()
    $url
    while ($true) {
        $context = $listener.GetContext()
        $request = $context.Request
        $response = $context.Response
        if($request.HttpMethod -eq "GET"){
            # GET時にはHello, world!を返す
            $text = "Hello, world!" 
        }elseif($request.HttpMethod -eq "POST"){
            # POST時には受け取った文字列をそのまま返す(エンコーディングは考慮しない)
            $reader = New-Object System.IO.StreamReader($request.InputStream)
            $text = $reader.ReadToEnd()
            $reader.Close()
        }else{
            # PUTなどには未対応。必要に応じて上記のelseifを参考によしなにすること
            $response.StatusCode = 400 # Bad request
            $response.Close()
            continue
        }
        $bytes = [System.Text.Encoding]::UTF8.GetBytes($text)
        $response.ContentLength64 = $bytes.Length
        $output = $response.OutputStream
        $output.Write($bytes, 0, $bytes.Length)
        $output.Close()
    }
} finally {
    $listener.Stop()
    $listener.Dispose()
}

Powershellから動作確認する例

GET

$uri = "http://127.0.0.1:8080/" 
[System.Text.Encoding]::UTF8.GetString($(Invoke-WebRequest $uri).Content)
#Hello, world!

POST

$uri = "http://127.0.0.1:8080/" 
$body = [System.Text.Encoding]::UTF8.GetBytes("Hello, world!")
Invoke-RestMethod -Method POST -Uri $uri -Body $body
#Hello, world!

参考資料

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?