LoginSignup
6
1

More than 5 years have passed since last update.

curl で Header と遊ぶ

Last updated at Posted at 2017-08-06
1 / 9
$ curl -v http://localhost:18888
request
> GET / HTTP/1.1
> Host: localhost:18888
> User-Agent: curl/7.51.0
> Accept: */*
response
< HTTP/1.1 200 OK
< Date: Sun, 06 Aug 2017 06:03:48 GMT
< Content-Length: 32
< Content-Type: text/html; charset=utf-8
<
<html><body>hello</body></html>
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact

これが Response Header

> Host: localhost:18888
> User-Agent: curl/7.51.0
> Accept: */*

field name と value で成り立っています。


http://localhost:18888/?foo=bar へリクエストをするには、以下のような方法があります。-G は メソッドを GET に指定するためです。

curl -G -d "foo=bar" http://localhost:18888
curl -G --data "foo=bar" http://localhost:18888
curl -G --data-urlencode "foo=bar" http://localhost:18888

違いは何でしょう?


--data-urlencode のみが、URLをエンコードしてくれますので、スペースありなどのクエリをおくるときはこれを使います。

curl -G --data-urlencode "foo=bar baz" http://localhost:18888

X- をプレフィックスとした field name はアプリケーションが自由に使ってよいことになっています。

GitHub の Webhook などでは、X-GitHub-Event のような Header があったりします。


X-Foo: bar

上の Header を送信する curl はどのようなものでしょうか?


curl -H "X-Foo: bar" http://localhost:18888/
#or
curl --header "X-Foo: bar" http://localhost:18888/

とすれば、以下のようなリクエストを送信できます。

GET / HTTP/1.1
Host: localhost:18888
Accept: */*
User-Agent: curl/7.51.0
X-Foo: bar

最後に json を送る curl を紹介します。

curl -d "{\"foo\":\"bar\"}" \
  -H "Content-Type: application/json" \
  http://localhost:18888

-d オプションのデフォルト Content-Type は x-www-form-urlencoded となってしまいますので、application/json と指定しています。

6
1
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
6
1