A note on how to communicate with HTTP in Python. (For Python3 series)
In Dive Into Python 3, the Python standard "[urllib.request](http://docs.python.jp/3.5/" How to use "library / urllib.request.html)" and how to use a third party "httplib2" are introduced, and httplib2 is recommended, but I myself I want to use genuine as much as possible, and I do not need a function that can be used only with httplib2, so I will try using urllib.request for the time being.
Use the urlopen function of the urllib.request module. Just specify the URL as an argument. If you don't need to encode the request parameter, you can write "? Param1 = value1 & param2 = value2" after the URL.
The response is a http.client.HTTPResponse object, so use the read () function to get the response body. To get.
Postal code search API provided by Ibis Co., Ltd. as a trial Try to hit.
http_get.py
import urllib.request
with urllib.request.urlopen("http://zipcloud.ibsnet.co.jp/api/search?zipcode=4200855") as res:
html = res.read().decode("utf-8")
print(html)
If the request parameter includes Japanese etc., it is necessary to encode it. It seems easy to do with the urlencode () function of the "urllib.parse" module. The argument is a dictionary type, and if multiple items are stored, it will automatically become a parameter string connected by &. (No leading?)
Fixed the above zip code search parameters to be specified this way. (Since it's only ASCII, there's no need to encode it ...)
http_get2.py
import urllib.request
import urllib.parse
#Encode request parameters
params = {"zipcode":"4200855"}
encodedParams = urllib.parse.urlencode(params)
#API call with encoded request parameters
with urllib.request.urlopen("http://zipcloud.ibsnet.co.jp/api/search?" + encodedParams) as res:
html = res.read().decode("utf-8")
print(html)
Recommended Posts