HTTP GET/POST Get HTTP GET information from the server. Returns a JSON file etc. HTTP POST sends information to the server. Nothing in particular returns (success, failure may be returned)
For those who can use HTTP GET / POST with cURL (command) but don't know how to put it into programming (Python). Python uses the Python3 urllib library.
HTTP GET Multiple headers have also been added. "-H" is the 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
Multiple data have been added. This data is sent to the server. "-D" is the 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)
I don't know the details of HTTP GET / POST, so I kept it to a minimum, but I think the coat itself is correct. Find out more about HTTP GET / POST elsewhere. I think that it will come out if you use API etc.
Recommended Posts