python http.client 发起http请求

1.建立连接(TCP)
2.发起请求—开始传输
3.获取响应
4.获取响应正文
5.关闭连接

作用:模拟客户端、浏览器向服务器发起http请求的过程

实例1:

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()

实例2:

def get_networks(ignore_error=False):
    """
    Get list of active ZeroTier networks.
    """
    auth_token = get_auth_token()
    if auth_token is None:
        return []

    conn = HTTPConnection("localhost", 9993)
    path = "/network"
    headers = {
        "X-ZT1-Auth": auth_token
    }
    conn.request("GET", path, "", headers)
    res = conn.getresponse()
    data = json.loads(res.read())

    # nwid field is deprecated, so make sure id field exists.
    for network in data:
        if 'id' not in network and 'nwid' in network:
            network['id'] = network['nwid']

    return data 

实例3:

def test_http_over_https(self):
        if self.scheme != 'https':
            return self.skip('skipped (not running HTTPS)... ')

        # Try connecting without SSL.
        conn = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
        conn.putrequest('GET', '/', skip_host=True)
        conn.putheader('Host', self.HOST)
        conn.endheaders()
        response = conn.response_class(conn.sock, method='GET')
        try:
            response.begin()
            self.assertEqual(response.status, 400)
            self.body = response.read()
            self.assertBody('The client sent a plain HTTP request, but this '
                            'server only speaks HTTPS on this port.')
        except socket.error:
            e = sys.exc_info()[1]
            # "Connection reset by peer" is also acceptable.
            if e.errno != errno.ECONNRESET:
                raise 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值