您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页Python封装 HTTP POST和Get请求方法

Python封装 HTTP POST和Get请求方法

来源:二三娱乐

get请求方法

    def get(self, url, params):
        params = urllib.parse.urlencode(eval(params))  # 将参数转为url编码字符串
        url = 'http://' + self.host + ':' + str(self.port)  + url + params
        request = urllib.request.Request(url, headers=self.headers)

        try:
            response = urllib.request.urlopen(request)
            response = response.read().decode('utf-8')  ## decode函数对获取的字节数据进行解码
            json_response = json.loads(response)  # 将返回数据转为json格式的数据
            return json_response
        except Exception as e:
            print('%s' % e)
            return {}

post请求方法

    def post(self, url, data):
        data = json.dumps(eval(data))
        data = data.encode('utf-8')
        url = 'http://' + self.host + ':' + str(self.port)  + url
        try:
            request = urllib.request.Request(url, headers=self.headers)
            response = urllib.request.urlopen(request, data)
            response = response.read().decode('utf-8')
            json_response = json.loads(response)
            return json_response
        except Exception as e:
            print('%s' % e)
            return {}

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务