python获取非200的http状态码

这段代码展示了如何使用Python进行HTTP请求,并处理可能出现的HTTPError异常。它使用了`urllib`库来构建请求,设置请求头,进行URL编码,并处理POST请求的数据。在发送请求时,代码会尝试捕获HTTPError异常,并打印出错误信息。此外,还进行了SSL证书验证的配置。
摘要由CSDN通过智能技术生成

添加异常捕获:except urllib.error.HTTPError as e:
print(e.read().decode(“UTF-8”))

# -*- coding: utf-8 -*-
from __future__ import print_function
import ssl, hmac, base64, hashlib
import urllib
from datetime import datetime as pydatetime
try:
    from urllib import urlencode, request
    from urllib2 import Request, urlopen
except ImportError:
    from urllib.parse import urlencode
    from urllib.error import HTTPError
    from urllib.request import Request, urlopen

# 云市场分配的密钥Id
secretId = "asdfasdfasfasdfasdfsdfasdfs"
# 云市场分配的密钥Key
secretKey = "trwrtrtwertqertqwerqetrywertwqer"
source = "market"

# 签名
datetime = pydatetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
signStr = "x-date: %s\nx-source: %s" % (datetime, source)
sign = base64.b64encode(hmac.new(secretKey.encode('utf-8'), signStr.encode('utf-8'), hashlib.sha1).digest())
auth = 'hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"' % (
secretId, sign.decode('utf-8'))

# 请求方法
method = 'POST'
# 请求头
headers = {
    'X-Source': source,
    'X-Date': datetime,
    'Authorization': auth,

}
# 查询参数
queryParams = {
}
# body参数(POST方法下存在)
bodyParams = {
    "a": "1234567890",
    "pageindex": "1",
    "b": "张三"
}
# url参数拼接
url = 'https://www.xxx.com/release/xxx'
if len(queryParams.keys()) > 0:
    url = url + '?' + urlencode(queryParams)

request = Request(url, headers=headers)
request.get_method = lambda: method
if method in ('POST', 'PUT', 'PATCH'):
    request.data = urlencode(bodyParams).encode('utf-8')
    request.add_header('Content-Type', 'application/x-www-form-urlencoded')
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

try:
    response = urlopen(request, context=ctx)
    print(response)
    content = response.read()

    if content:
        print(content.decode('utf-8'))
except urllib.error.HTTPError as e:
	# 用异常捕获,http状态码非200时,可解析出响应体
    print(e.read().decode("UTF-8"))
# -*- coding: utf-8 -*-
from __future__ import print_function
import ssl, hmac, base64, hashlib
import urllib
from datetime import datetime as pydatetime
try:
    from urllib import urlencode, request
    from urllib2 import Request, urlopen
except ImportError:
    from urllib.parse import urlencode
    from urllib.error import HTTPError
    from urllib.request import Request, urlopen

# 云市场分配的密钥Id
secretId = "asdfasdfasfasdfasdfsdfasdfs"
# 云市场分配的密钥Key
secretKey = "trwrtrtwertqertqwerqetrywertwqer"
source = "market"

# 签名
datetime = pydatetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
signStr = "x-date: %s\nx-source: %s" % (datetime, source)
sign = base64.b64encode(hmac.new(secretKey.encode('utf-8'), signStr.encode('utf-8'), hashlib.sha1).digest())
auth = 'hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"' % (
secretId, sign.decode('utf-8'))

# 请求方法
method = 'POST'
# 请求头
headers = {
    'X-Source': source,
    'X-Date': datetime,
    'Authorization': auth,

}
# 查询参数
queryParams = {
}
# body参数(POST方法下存在)
bodyParams = {
    "a": "1234567890",
    "pageindex": "1",
    "b": "张三"
}
# url参数拼接
url = 'https://www.xxx.com/release/xxx'
if len(queryParams.keys()) > 0:
    url = url + '?' + urlencode(queryParams)

data = urllib.parse.urlencode(bodyParams).encode('utf-8')
print(data)
# data参数如果要传必须传bytes(字节流)类型的,如果是一个字典,先用urllib.parse.urlencode()编码。
request = urllib.request.Request(url=url, data=data, headers=headers, method='POST')

try:
    response = urllib.request.urlopen(request)
    print(response.status)
    print(response.msg)
    html = response.read().decode('utf-8')
    print(html)
except HTTPError as e:
    
    print(e.read().decode("UTF-8"))




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值