urllib2 基本的发送请求

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值