urllib2 使用方法:
def http_post_json(url, req_data=None, header=None):
code = -1
error = ''
data={}
req_data = {} if req_data is None else req_data
header = {} if header is None else header
request = urllib2.Request(url)
request.add_header('Content-Type', 'application/json')
for k, v in header.items():
request.add_header(k, v)
try:
resp = urllib2.urlopen(request, json_helper.dumps(req_data)).read()
data = json_helper.loads(resp)
except HTTPError, e:
code = e.code
error = e.strerror
except Exception, e:
error = str(e)
finally:
return code, error, data
调用:
code, error, data = http_post_json(url路径,
req_data={"键1": "值1",
"键2": "值2"})
requests 的保存cookies的调用
data = json.dumps({"tab":"50"})
headers = {
"Content-Type": "application/json;charset=UTF-8",
"自定义头字段": 自定义头字段值)
}
auth_msg = {'账号字段': 账号值, '密码字段': 密码值,可使用decrypt来加密, '其他参数': 其他参数值}
r_auth = requests.post(登录的url, params=auth_msg, headers=headers, verify=False, timeout=10)
# 设置超时规则,每1s去获取返回结果,结果为空或者查询未超过3s,继续等待1
timeout = 5
poll_seconds = 1
deadline = time.time() + timeout
while time.time() < deadline and not r_auth.status_code:
time.sleep(poll_seconds)
if not r_auth.status_code:
return str(ErrorCode.SYS_ERR)
# 认证成功后再次请求更新task状态接口推送虚拟机创建信息
r = requests.post(url, params=data, headers=headers, cookies=r_auth.cookies, verify=False)
# 设置超时规则,每1s去获取返回结果,结果为空或者查询未超过3s,继续等待1
timeout = 5
poll_seconds = 1
deadline = time.time() + timeout
while time.time() < deadline and not r.status_code:
time.sleep(poll_seconds)
if not r.status_code:
return str(ErrorCode.SYS_ERR)
return str(r.status_code)
转载url:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html