Python 3.5.2 + Windows 7環境下windows
第一種:http.client方式api
def http_client_post(): conn = http.client.HTTPSConnection("www.xxx.com") params = urllib.parse.urlencode( {'id': 'id', 'token':'token', } ) conn.request("POST", "/api/get-product", params, headers={"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}) resp=conn.getresponse() print(resp.read().decode("UTF-8")) conn.close()
第二種:urllib.request方式,urllib是基於http包的app
def urllib_post(): opener = urllib.request.build_opener() params = urllib.parse.urlencode( {'id': 'id', 'token': 'token', } ) with opener.open('https://www.xxx.com/api/get-product', data=bytes(params, 'utf-8')) as resp: print(resp.read().decode('utf-8'))
經測試第二種方式在windows 2008下盡然會出HTTP400錯,WIN7下是OK的,看到Python的底層庫還不太行啊
第三種:用第三方requests庫,推薦用這種方式
你會看到requests庫在pypi庫中下載量排名很高http://pypi-ranking.info/alltime,對於英文閱讀不是很好的朋友,官方還有中文版文檔,看一下這吊炸天的代碼: post
def requests_post(): params = {'id': 'id', 'token': 'token'} r = requests.post("https://www.xxx.com/api/get-product", data=params) print(r.text)
原文:https://blog.csdn.net/iteye_12715/article/details/82678017測試