Python网络编程

Python请求状态代码

Python请求状态代码详细操作教程
在接收并解释了请求消息后,服务器将以HTTP响应消息进行响应。响应消息具有状态码。它是一个三位数的整数,其中状态码的第一位数定义了响应的类别,而后两位则没有任何分类作用。第一位数字有5个值:

状态码

编号 状态码 描述
1 1xx: Informational 表示已收到请求,并且该过程正在继续。
2 2xx: Success 表示已成功接收,理解并接受了该动作。
3 3xx: Redirection 表示采取进一步的措施才能完成请求。
4 4xx: Client Error 表示请求包含不正确的语法或无法实现。
5 5xx: Server Error 表示服务器无法满足看似有效的请求。

成功响应

在下面的示例中,我们从URL访问文件,并且响应成功。所以返回的状态码是200:
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-25
import urllib3
http = urllib3.PoolManager()
resp = http.request('GET', 'https://lidihuo.com/robots.txt')
print resp.data
# get the status of the response
print resp.status
执行上面代码,得到以下结果:
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-25
User-agent: *
Disallow: /admin/

不成功响应

在下面的示例中,我们从不存在的url访问文件。响应不成功。因此,返回的状态码是403。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-25
import urllib3
http = urllib3.PoolManager()
resp = http.request('GET', 'https://lidihuo.com/robot1.txt')
print resp.data
# get the status of the response
print resp.status
执行上面代码,得到以下结果:
<html>
<body>
<h1>Whitelabel Error Page</h1>
<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>
<div id='created'>Tue Aug 25 11:39:56 CST 2020</div>
<div>There was an unexpected error (type=Bad Request, status=400).</div>
<div>Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "robots1.txt"</div>
</body>
</html>
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4