利用urllib.request模板向指定的URL(http://httpbin.org/anything)发送请求,获取相应内容、响应码以及响应头信息。 import urllib.request #向指定的URL发送请求,获取相应
时间: 2023-12-06 09:43:11 浏览: 156
内容、响应码以及响应头信息的示例代码如下:
```python
import urllib.request
url = "http://httpbin.org/anything"
req = urllib.request.Request(url)
# 添加请求头信息
req.add_header("User-Agent", "Mozilla/5.0")
# 发送请求并获取响应
response = urllib.request.urlopen(req)
# 获取响应内容
content = response.read().decode("utf-8")
# 获取响应码
status_code = response.status
# 获取响应头信息
headers = dict(response.getheaders())
print("响应内容:", content)
print("响应码:", status_code)
print("响应头信息:", headers)
```
运行以上代码,将会输出类似如下的结果:
```
响应内容: {
"args": {},
"data": "",
"files": {},
"form": {},
"headers": {
"Accept-Encoding": "identity",
"Host": "httpbin.org",
"User-Agent": "Mozilla/5.0",
"X-Amzn-Trace-Id": "Root=1-616d46a3-2a12c00d4546d5f02e9f7225"
},
"json": null,
"method": "GET",
"origin": "114.94.11.186",
"url": "http://httpbin.org/anything"
}
响应码: 200
响应头信息: {'Date': 'Tue, 19 Oct 2021 09:12:35 GMT', 'Content-Type': 'application/json', 'Content-Length': '331', 'Connection': 'close', 'Server': 'gunicorn/19.9.0', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true'}
```
其中,"响应内容"是请求响应内容的JSON格式,"响应码"是HTTP响应状态码,"响应头信息"是HTTP响应头信息的字典形式。
阅读全文