あまブログ

ドキドキ......ドキドキ2択クイ〜〜〜〜〜〜〜ズ!!

telnetでGETとPOSTでHTTPリクエストを送る方法

この記事では、クライアントからtelnetを使ってGETメソッドとPOSTメソッドでWebサーバにHTTPリクエストを送信する方法を紹介します。

HTTPは、Webサーバ(サーバ)⇄Webブラウザ(クライアント)間のWebページの送受信に使われるプロトコルです。

環境

  • macOS Monterey:12.4

手順

1. telnetのインストール

$ brew install telnet

2. GETメソッド

以下のコマンドで、example.comの80番ポート(HTTP)に接続

$ telnet example.com 80

書式:telnet <ホスト名> <ポート番号>

続けて、以下のHTTPリクエストを実行

GET / HTTP/1.1 # リクエスト行
Host:  example.com # ヘッダ
<改行>
  • リクエスト行
    • メソッド:GETメソッド、リクエストURI:/、プロトコルバージョン:HTTP/1.1
  • ヘッダ
    • フィールド名:Host、フィールド値:example.com
      • Host→HTTP/1.1 で唯一の必須ヘッダ。フィールド値にURLのホスト部分を指定。
  • <改行>
    • 1行空けることでヘッダの終わりを伝える

3. POSTメソッド

xxx.com/articlesに以下のようなフォームがある場合を想定

<form action="/articles" method="post">
  <div>
    <label for="article_title">Title</label>
    <input type="text" name="article[title]" id="article_title">
  </div>
  <div>
    <label for="article_body">Body</label>
    <textarea type="text" name="article[body]" id="article_body"></textarea>
  </div>
  <div>
    <input type="submit" name="commit" value="Submit" data-disable-with="Submit">
  </div>
</form>

以下のコマンドで、xxx.comの80番ポート(HTTP)に接続

$ telnet xxx.com 80

続けて、以下のHTTPリクエストを実行

POST /articles HTTP/1.1 # リクエスト行
Host: xxx.com # ヘッダ
Content-Length: 35 # ヘッダ
<改行>
article[title]=Hi&article[body]=Mom # メッセージボディ
  • リクエスト行
    • POSTメソッド、パスに/articles、HTTPバージョン1.1を指定
  • ヘッダ
    • フィールド名→Host、フィールド値→example.com
    • フィールド名→Content-Length、フィールド値→35
      • Content-Length:コンテンツ(メッセージボディ)の長さをバイト単位で示す
  • <改行>
    • 1行空けることでヘッダの終わりを伝える
  • メッセージボディ
    • <inputタグのname属性の値>=<テキスト>&<inputタグのname属性の値>=<テキスト>&...

【参考】