LoginSignup
3
3

More than 3 years have passed since last update.

HTTPのGET/POSTをcURL(コマンド)とPython(プログラミング)で比較

Last updated at Posted at 2020-11-17

HTTP GET/POST

HTTPのGETをサーバーから情報を取得してきます。JSONファイルなどを返してくれる
HTTPのPOSTはサーバーに情報を送ります。特に返ってくるものはない(成功、失敗が返ってくることがある)

cURLとPython

cURL(コマンド)でHTTPのGET/POSTを使えるけどプログラミング(Python)に落とし込める方法がわからない人向けです。
PythonはPython3のurllibライブラリを使用しています。

HTTP GET

複数のheaderも付け加えられています。
「-H」がcURLのheaderです。

curl -X GET "https://example.com/api/" -H "accept: application/json" -H "Content-Type: form"
from urllib.parse import urlencode
from urllib.request import urlopen, Request

url = "https://example.com/api/"

headers = {
    "accept" :"application/json",
    "Content-Type" :"application/x-www-form-urlencoded"
}

request= Request(url, headers=headers)

with urlopen(request) as response:
    body= response.read()
    print(body)

HTTP POST

複数のdataが付け加えられています。このdataがサーバーに送信されます。
「-d」がcURLのdataです。


curl -X POST "https://example.com/api/" -H "accept: application/json" -d "temperature=18" -d "operation_mode=auto"
from urllib.parse import urlencode
from urllib.request import urlopen, Request

url = "https://example.com/api/"

headers = {
    "accept" :"application/json"
}

request = Request(url, headers=headers)

data = {
    "temperature": "18",
    "operation_mode": "auto",
}

data = urlencode(data).encode("utf-8")

response = urlopen(request, data)

あとがき

HTTP GET/POSTは詳しくはわかっていないため最小限の説明に抑えましたが、コート自体はあっていると思います。
HTTP GET/POSTのことは他で調べてみて下さい。APIなどを利用すると出てくると思います。

3
3
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
3
3