本篇主要记录下使用python的requests模块发送GET请求的实现代码.
向服务器发送get请求:
无参数时:r = requests.get(url)
带params时:r = requests.get(url,params=params)
带params和headers时:r = requests.get(url,params=params,headers=headers)
代码如下:
#coding=utf-8 import unittest import requests class GetTest(unittest.TestCase): def setUp(self): host = 'https://httpbin.org/' endpoint = 'get' self.url = ''.join([host, endpoint]) def test1(self): u'''get无参数测试''' r1 = requests.get(self.url)# 向服务器发送请求 code = r1.status_code #状态码 self.assertEqual(200,code) print(r1.text) # unicode型文本 def test2(self): u'''get带参数测试''' params = {'show_env': '1'} r2 = requests.get(self.url,params=params) self.assertEqual(200, r2.status_code) def test3(self): u'''get带参数、带headers测试''' params = {'show_env': '8'} headers = {'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*','User-Agent': 'python-requests/2.18.3'} r = requests.get(self.url, params=params,headers=headers) r3 = r.json() print(r3) connect = r3.get('headers').get('Connection') self.assertEqual('close', connect) #断言 校验header里的Connection值 def tearDown(self): pass if __name__ == "__main__": unittest.main()