python3 http.client 网络请求

python3 http.client 网络请求

一:get 请求

 

复制代码
'''
Created on 2014年4月21日

@author: dev.keke@gmail.com
'''
import http.client

#简单的GET请求
con = http.client.HTTPConnection('www.baidu.com')
con.request("GET", "/index.html",'',{})
resu = con.getresponse()
print(resu.status,resu.reason,resu.info())  #打印读取到的数据

#打印读取的数据
print (resu.read())

#测试一个无效的请求
inCon = http.client.HTTPConnection('www.baidu.com')
inCon.request('GET', 'None.html')
resu2 = inCon.getresponse()
print('\n')
print(resu2.status,resu2.msg)
复制代码

二:POST 请求

   

复制代码
import http.client,urllib.parse

pararms = urllib.parse.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
conn = http.client.HTTPConnection("bugs.python.org")
conn.request('POST', '', pararms, headers)
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data)

conn.close()
复制代码

   打印结果 :

  

302 Found
b'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'

三: head 请求

复制代码
>>> import http.client
>>> conn = http.client.HTTPConnection("www.python.org")
>>> conn.request("HEAD","/index.html")
>>> res = conn.getresponse()
>>> print(res.status, res.reason)
200 OK
>>> data = res.read()
>>> print(len(data))
0
>>> data == b''
True
复制代码

四:put 请求

 

复制代码
>>> # This creates an HTTP message
>>> # with the content of BODY as the enclosed representation
>>> # for the resource http://localhost:8080/file
...
>>> import http.client
>>> BODY = "***filecontents***"
>>> conn = http.client.HTTPConnection("localhost", 8080)
>>> conn.request("PUT", "/file", BODY)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
200, OK
复制代码

 

参考:https://docs.python.org/3.4/library/http.client.html?highlight=http.client#module-http.client

posted @   cocoajin  阅读(15051)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示