欢迎访问宙启技术站
智能推送

Python中HTTP请求的错误处理和异常处理

发布时间:2024-01-07 04:05:39

在Python中进行HTTP请求时,可能会发生一些错误和异常,需要进行错误处理和异常处理。下面是一些常见的HTTP请求错误和异常,以及如何进行处理的示例。

1. 响应状态码非200

当发送HTTP请求后,如果服务器返回的响应状态码不等于200,表示请求出现错误。可以使用requests库来发送HTTP请求,并通过response.status_code来获取响应状态码。以下是一个处理状态码非200的示例:

import requests

url = 'http://example.com'

try:
    response = requests.get(url)
    if response.status_code == 200:
        print('请求成功')
    else:
        print('请求失败,状态码:', response.status_code)
except requests.exceptions.RequestException as e:
    print('请求发生异常', str(e))

2. 连接超时

在发送HTTP请求时,如果连接超时,可能是由于网络不稳定或服务器响应较慢造成的。可以使用requests库的timeout参数来设置连接超时时间,并通过requests.exceptions.Timeout捕获超时异常。以下是一个处理连接超时的示例:

import requests

url = 'http://example.com'
timeout = 10

try:
    response = requests.get(url, timeout=timeout)
    print('请求成功')
except requests.exceptions.Timeout as e:
    print('连接超时', str(e))
except requests.exceptions.RequestException as e:
    print('请求发生异常', str(e))

3. 请求异常

在发送HTTP请求时,可能出现各种异常情况,比如域名解析失败、网络连接异常等。可以使用requests.exceptions.RequestException捕获所有请求异常。以下是一个处理请求异常的示例:

import requests

url = 'http://example.com'

try:
    response = requests.get(url)
    print('请求成功')
except requests.exceptions.RequestException as e:
    print('请求发生异常', str(e))

4. 代理异常

在发送HTTP请求时,可以使用代理来隐藏真实IP地址。如果使用了代理,但代理无法连接或无效,则会发生代理异常。可以使用requests.exceptions.ProxyError异常来捕获代理异常。以下是一个处理代理异常的示例:

import requests

url = 'http://example.com'
proxies = {
    'http': 'http://your-proxy',
    'https': 'http://your-proxy'
}

try:
    response = requests.get(url, proxies=proxies)
    print('请求成功')
except requests.exceptions.ProxyError as e:
    print('代理发生异常', str(e))
except requests.exceptions.RequestException as e:
    print('请求发生异常', str(e))

5. SSL证书验证异常

在发送HTTPS请求时,可以通过设置verify参数来验证SSL证书。如果SSL证书验证失败,则会发生SSL证书验证异常。可以使用requests.exceptions.SSLError异常来捕获SSL证书验证异常。以下是一个处理SSL证书验证异常的示例:

import requests

url = 'https://example.com'

try:
    response = requests.get(url, verify=False)  # 禁用SSL证书验证
    print('请求成功')
except requests.exceptions.SSLError as e:
    print('SSL证书验证异常', str(e))
except requests.exceptions.RequestException as e:
    print('请求发生异常', str(e))

除了上述示例外,对于其他具体的HTTP请求错误和异常,可以根据具体情况进行相应的处理。通过适当的错误处理和异常处理,可以增加程序的健壮性,提高用户体验。