1. 程式人生 > >python_HTTP(實現GET、PUT、POST、DELETE操作)

python_HTTP(實現GET、PUT、POST、DELETE操作)

第一篇博文,剛開始學Python,記錄一下自己實現的指令碼,若有不準確的地方請指正!

目標:用Python實現HTTP請求

工具:PyCharm2016.1.4

語言:Python3.4

1、HTTP操作:GET、DELETE、PUT、POST

2、測試環境:首先開啟伺服器與客戶端的互動程序,本文中服務端和客戶端都是linux系統實現的

3、可以下載谷歌的外掛POSTMAN與Python實現對比

4、Python指令碼

#-*- encoding: utf-8 -*-
from http import client
from urllib import request,parse


class 
HTTP: def __init__(self,url,gwid=""): self.url=url self.GWID=gwid def GET_info(self): header = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-cn,zh;q=0.8", "Connection": "keep-alive", } conn = client.HTTPConnection(self
.url) allurl = "/router/" + self.GWID + "/wans" print(allurl) conn.request(method="GET", url=allurl, headers=header) rl = conn.getresponse() data = rl.read() host_info = data.decode("utf-8") print(host_info) def POST_info(self): header = { "Accept"
: "*/*", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-cn,zh;q=0.8", "Connection": "keep-alive", } bodydata ='''{ "state":"up", "event":"reboot", "strategy":"week", "date":"1", "time":"15:00", "comment":"" }''' print(bodydata) conn = client.HTTPConnection(self.url) allurl = "/router/"+self.GWID+"/power/schedule" print(allurl) conn.request(method="POST", url=allurl, body=bodydata,headers=header) rl = conn.getresponse() data = rl.read() host_info = data.decode("utf-8") print(host_info) def PUT_info(self): header = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-cn,zh;q=0.8", "Connection": "keep-alive", } bodydata = '''{ "state":"up", "event":"reboot", "strategy":"week", "date":"2", "time":"15:00", "comment":"" }''' print(bodydata) conn = client.HTTPConnection(self.url) allurl = "/router/" + self.GWID + "/power/schedule/1" print(allurl) conn.request(method="PUT", url=allurl, body=bodydata, headers=header) rl = conn.getresponse() data = rl.read() host_info = data.decode("utf-8") print(host_info) def DELETE_info(self): header = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-cn,zh;q=0.8", "Connection": "keep-alive", } conn = client.HTTPConnection(self.url) allurl = "/router/" + self.GWID + "/power/schedule/2" print(allurl) conn.request(method="DELETE", url=allurl, headers=header) rl = conn.getresponse() data = rl.read() host_info = data.decode("utf-8") print(host_info) if __name__=="__main__": url="192.200.200.3:2049" gwid="b28b8b51399fcfa5c0e96164e20d38c5" hp=HTTP(url,gwid) hp.PUT_info()