18.7.3 Examples
Here is an example session that uses the "GET" method:
>>> import httplib
>>> conn = httplib.HTTPConnection("www.python.org")
>>> conn.request("GET", "/index.html")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK
>>> data1 = r1.read()
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print r2.status, r2.reason
404 Not Found
>>> data2 = r2.read()
>>> conn.close()
Here is an example session that shows how to "POST" requests:
>>> import httplib, urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
... "Accept": "text/plain"}
>>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80")
>>> conn.request("POST", "/cgi-bin/query", params, headers)
>>> response = conn.getresponse()
>>> print response.status, response.reason
200 OK
>>> data = response.read()
>>> conn.close()
分享到:
相关推荐
Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python What’s New In ...
conn = http.client.HTTPConnection("api.example.com") conn.request("POST", "/send-sms", {"phone": "1234567890"}) response = conn.getresponse() data = response.read().decode() conn.close() ``` 在上述...
本书《Python标准库示例》(The Python Standard Library by Example)由资深Python专家Doug Hellmann编写,属于开发者图书馆系列的一部分。该系列书籍旨在为软件开发人员提供最新的编程语言和技术方面的高质量参考...
conn = http.client.HTTPConnection("example.com") conn.request("GET", "/") res = conn.getresponse() data = res.read() print(data.decode("utf-8")) ``` ##### 4. **aiohttp** - **简介**:`aiohttp`...
>>> h4 = http.client.HTTPConnection('www.python.org', 80, timeout=10) ``` `source_address`参数是在Python 3.2版本中添加的,而`strict`参数在3.4版本中被移除。 2. **HTTPSConnection** `...
conn = http.client.HTTPConnection("www.example.com") ``` ### 设置头部信息 HTTP请求头可以包含很多信息,如用户代理、编码格式等。在Python中,可以通过`set_request_header`方法设置头部信息: ```python ...
conn = http.client.HTTPConnection('www.baidu.com') conn.request('GET', '/') response = conn.getresponse() html = response.read().decode('utf-8') conn.close() print(html) ``` 以上就是Python爬虫...
conn = httplib.HTTPConnection(url) conn.request('GET', '/', headers=HEADERS) response = conn.getresponse() data = response.read() # 这里可以处理下载到的数据,例如保存到文件等 conn.close() def ...
http.client.HTTPConnection.debuglevel = 1 response = requests.get('http://httpbin.org/get') print(response.text) ``` #### 技巧7:使用grequests实现异步请求 对于高并发场景,使用`grequests`库可以帮助...
conn = httplib.HTTPConnection("www.example.com") ``` 2. **发送请求**:然后,你可以调用`conn.request()`方法来发送HTTP请求。它接受四个参数:请求方法(如"GET"或"POST")、URL、请求头(可选)和请求体...
conn = ahttplib.HTTPConnection("example.com") conn.request("GET", "/path/to/resource") response = conn.getresponse() print(response.status, response.reason) data = response.read() conn.close() ``` ...