Python requests庫使用
阿新 • • 發佈:2021-06-19
1、requests安裝
pip install requests
import requests 如果沒有報錯,說明requests安裝成功了。
3、建立Python工程
使用Idea,安裝Python外掛
建立工程,選擇Python,工程名稱為pythondemon
在工程名稱上右鍵,點選New-> Python File.
4、建立mock介面
http://www.mockhttp.cn/mock/logon
返回{ "code": 0, "message": "OK" }
使用Get請求呼叫
import requests, json ori=requests.get('http://www.mockhttp.cn/mock/logon') print(ori.json())
使用POST請求
import requests, json ori=requests.post('https://www.fastmock.site/mock/80a256fd71635691b5e37ef11ba0baca/user/logon') print(ori.json())
POST優化
import requests, json url="https://www.fastmock.site/mock/80a256fd71635691b5e37ef11ba0baca/user/logon" data={ "username": "zhangsan", "password": "123456" } def send_post(url, data): res = requests.post(url, data) return res.json() print(send_post(url,data))
5、使用類對POST和GET進行封裝
import requests, json class RunHttp: # 構造方法 def __init__(self, url, method, data=None): self.result = self.send_http(url, method, data) # print(self.result) def send_get(self,url, data): res = requests.get(url, data) return res.json() def send_post(self,url, data): res = requests.post(url, data) return res.json() def send_http(self,url, method,data=None): print("method=" + method) if 'GET' == method: return self.send_get(url, data) else: return self.send_post(url, data) if __name__ == '__main__': url="https://www.fastmock.site/mock/80a256fd71635691b5e37ef11ba0baca/user/logon" data={ "username": "zhangsan", "password": "123456" } run = RunHttp(url, 'POST', data) print(run.result)