- 建立连接(TCP)
- 发起请求—开始传输
- 获取响应
- 获取响应正文
- 关闭连接
作用:模拟客户端、浏览器向服务器发起http请求的过程
import http.client #导包
class test():
def __init__(self):
self.host = "localhost"
self.port = 8080
# get请求
def get_homepage(self):
# 建立连接,传域名/ip+端口
con = http.client.HTTPConnection(self.host,self.port)
# 发起请求,请求方式,url
con.request("GET","/myproject/")
# 获取响应
res = con.getresponse()
# 获取响应正文
content = res.read().decode("utf8")
print(content)
# 断言
if "米乐熊" in content:
print("通过")
else:
print("失败")
con.close()
# post请求
def login(self):
con = http.client.HTTPConnection(self.host,self.port)
url = "http://localhost:8080/myproject/user/login"
body = "username=admin&password=admin123&verifycode=0000"
headers = {"Content-Type":" application/x-www-form-urlencoded; charset=UTF-8"}
con.request("POST",url,body=body,headers=headers)
res = con.getresponse()
content = res.read().decode()
if content == "login-pass":
print("通过")
else:
print("失败")
con.close()
def add(self):
con = http.client.HTTPConnection(self.host,self.port)
url = "/myproject/customer/add"
body = "customername=未和&customerphone=111111&childsex=男&childdate=2019-10-10&creditkids=0&creditcloth=0"
headers = {"Content-Type":" application/x-www-form-urlencoded; charset=UTF-8","Cookie": "JSESSIONID=5069420EFDF92B5392596AA73508FBED; _jfinal_captcha=b7756b3da0e647b6a257a276c80ad066; username=admin; password=admin123"}
con.request("POST",url,body=body.encode("utf8"),headers=headers)
res = con.getresponse()
content = res.read().decode()
print(content)
con.close()
if __name__ == '__main__':
te = test()
te.login()