如何用Python写一个http post请求
1个回答
2016-12-18
展开全部
可以参考如下三种方法:
一、application/x-www-form-urlencoded
import urllib
url = "http://www.example.com"
body_value = {"package": "com.tencent.lian","version_code": "66" }
body_value = urllib.urlencode(body_value)
request = urllib2.Request(url, body_value)
request.add_header(keys, headers[keys])
result = urllib2.urlopen(request ).read()
二、multipart/form-data
需要利用python的poster模块,安装poster:pip install poster
代码:
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
url = "http://www.example.com"
body_value = {"package": "com.tencent.lian","version_code": "66" }
register_openers()
datagen, re_headers = multipart_encode(body_value)
request = urllib2.Request(url, datagen, re_headers)
# 如果有请求头数据,则添加请求头
request .add_header(keys, headers[keys])
result = urllib2.urlopen(request ).read()
二、application/json
import json
url = "http://www.example.com"
body_value = {"package": "com.tencent.lian","version_code": "66" }
register_openers()
body_value = json.JSONEncoder().encode(body_value)
request = urllib2.Request(url, body_value)
request .add_header(keys, headers[keys])
result = urllib2.urlopen(request ).read()
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询