LoginSignup
14
15

More than 5 years have passed since last update.

HTTP(S)プロトコルでデータを送信する方法いろいろ

Last updated at Posted at 2018-03-17

GETまたはPOSTを使うとき、最近のライブラリやフレームワークを使えば、id=123&title=hello{id: "123", title: "hello"}などいろいろな形式で自由にデータを送信することができる。

ただし内部的には厳格にフォーマットが決まっており、適切なリクエストヘッダとリクエストボディを組み合わせないとサーバーやクライアントが意図通りにデータを認識してくれないことがある。

GET /posts/123

URLパスの中で送信するデータを指定する。Railsや比較的最近のWebフレームワークでよく見かける形式。

GET /posts/123 HTTP/1.1
Host: example.com

GET /posts?id=123

URLのクエリパラメータを使って送信するデータを指定する。PerlやPHPで作ったシンプルなWebサイトや、昔ながらのWebサイトでよく見かける形式。

GET /posts?id=123 HTTP/1.1
Host: example.com

POST /create (リクエストボディにURLエンコードされたデータ)

リクエストボディを使って送信するデータを指定する。今も昔もいろいろなところでよく見かける形式。

POST /create HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

title=Hello&
text=This+is+a+pen.

POST /create (添付ファイルの送信)

リクエストボディにファイルのバイナリを入れてデータを送信する。Webページのformから添付ファイルを送信するときに使われている形式。

POST /upload HTTP/1.1
Content-Type: multipart/form-data; boundary=[boundary_str]
Content-Length: [size]

--[boundary_str]
Content-Disposition: form-data; name="image_file"; filename="image.png"
Content-Type: image/png

[cotent_bytes]
--[boundary_str]
Content-Disposition: form-data; name="image_title"

uploaded_image.png
--[boundary_str]--

POST /create (形式を指定せずバイナリを送る)

POST /upload HTTP/1.1
Content-Type: application/octet-stream

[contents_bytes]

POST /create (リクエストボディにJSON)

リクエストボディに送信するデータをJSONで入れる。APIを使ったデータのやり取りでよく使われる形式。

POST /posts
Content-Type: application/json

{"title":"Hello","body":"This is a pen."}

参考リンク

http://article.higlabo.com/ja/request_and_response.html
https://qiita.com/noboru_i/items/827b55b37b2d85e372df
https://murashun.jp/blog/20150920-01.html

14
15
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
14
15