Python Network Programming 简明教程
Python - Request Status Codes
在收到并解释请求消息后,服务器会通过 HTTP 响应消息进行响应。响应消息包含一个状态码。这是一个 3 位数的整数,其中状态码的第一位数字定义了响应的类型,而最后两位数字没有任何分类作用。第一位数字有 5 个值:
Status Codes
S.N. |
Code and Description |
1 |
*1xx:信息性*这意味着请求已被接收,且进程正在继续。 |
2 |
*2xx:成功*这意味着该操作已成功接收、理解并被接受。 |
3 |
*3xx:重定向*这意味着必须采取进一步措施才能完成请求。 |
4 |
*4xx:客户端错误*这意味着该请求包含不正确的语法或无法满足。 |
5 |
*5xx:服务器错误*这意味着服务器未能满足的一个明显有效的请求。 |
Successful Response
在下面的示例中,我们从一个 URL 访问一个文件,并且该响应是成功的。因此返回的状态码是 200。
import urllib3
http = urllib3.PoolManager()
resp = http.request('GET', 'http://tutorialspoint.com/robots.txt')
print resp.data
# get the status of the response
print resp.status
当我们运行以上程序时,我们得到以下输出:
User-agent: *
Disallow: /tmp
Disallow: /logs
Disallow: /rate/*
Disallow: /cgi-bin/*
Disallow: /videotutorials/video_course_view.php?*
Disallow: /videotutorials/course_view.php?*
Disallow: /videos/*
Disallow: /*/*_question_bank/*
Disallow: //*/*/*/*/src/*
200
Unsuccessful Response
在下面的示例中,我们从一个不存在的 URL 访问一个文件。该响应是失败的。因此返回的状态码是 403。
import urllib3
http = urllib3.PoolManager()
resp = http.request('GET', 'http://tutorialspoint.com/robot.txt')
print resp.data
# get the status of the response
print resp.status
当我们运行以上程序时,我们得到以下输出:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /robot.txt
on this server.</p>
</body></html>
403