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 {}