`

Python3下POST请求HTTPS链接

阅读更多

Python 3.5.2 + Windows 7环境下

第一种:http.client方式

 

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包的

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,对于英文阅读不是很好的朋友,官方还有中文版文档,看一下这吊炸天的代码:

def requests_post():
    params = {'id': 'id', 'token': 'token'}
    r = requests.post("https://www.xxx.com/api/get-product", data=params)
    print(r.text)

 

   

           

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics