LoginSignup
1
0

More than 1 year has passed since last update.

curlでPOSTする時にクエリストリングをURLエンコードする

Posted at

課題

curlには送信するデータをURLエンコードするための --data-urlencode オプションがあるが、これはPOSTリクエストにおいてリクエストボディにデータを追加するためのものである。
そのため、当たり前ではあるが、このオプションを付けてPOSTリクエストを送ってもクエリストリングではなくリクエストボディにURLエンコードしたデータが追加される。

$ curl localhost:50021 --data-urlencode text=こんにちは -v 
*   Trying 127.0.0.1:50021...
* Connected to localhost (127.0.0.1) port 50021 (#0)
> POST / HTTP/1.1
> Host: localhost:50021
> User-Agent: curl/7.79.1
> Accept: */*
> Content-Length: 50
> Content-Type: application/x-www-form-urlencoded

POSTリクエストを送る際にクエリストリングにURLエンコードした文字列を追加したい場合にはどうすれば良いのだろうか?

解決策

curlの--get オプションを追加することで、POSTリクエストにおいてクエリストリングにURLエンコードした文字列を追加することができる。

-G, --get
              When used, this option will make all data specified with -d, --data, --data-binary or --data-urlencode to be used in an HTTP GET request
              instead of the POST request that otherwise would be used. The data will be appended to the URL with a '?' separator.
$ curl localhost:50021 --get --data-urlencode text=こんにちは -v
*   Trying 127.0.0.1:50021...
* Connected to localhost (127.0.0.1) port 50021 (#0)
> GET /?text=%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF HTTP/1.1
> Host: localhost:50021
> User-Agent: curl/7.79.1
> Accept: */*
1
0
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
1
0