1. 程式人生 > 其它 >python get 請求_【Python】幾種POST/GET請求方式

python get 請求_【Python】幾種POST/GET請求方式

技術標籤:python get 請求

最近突發奇想想把我的QQ群訊息對接Zblog外掛移植到Python開發環境中,但是首先遇到的問題就是python如何進行POST請求並接收返回資料,其實很簡單,下面就羅列出幾種post請求的方法供大家參考

無需requests庫POST/GET請求

單純的post請求:

196b58e3-2c64-eb11-8da9-e4434bdf6706.svgPython

def http_post(): 
url = "http://text"
postdata = dict(d=2, p=10)
post = []
post.append(postdata)
req = urllib2.Request(url, json.dumps(post)) #需要是json格式的引數
req.add_header('Content-Type', 'application/json') #要非常注意這行程式碼的寫法
response = urllib2.urlopen(req)
result = json.loads(response.read())
print result

需要token時寫法如下:

196b58e3-2c64-eb11-8da9-e4434bdf6706.svgPython

def http_post(): 
url = "http://text"
postdata = dict(d=2, p=10)
post = []
post.append(postdata)
req = urllib2.Request(url, json.dumps(post))
access_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6I..........'
req.add_header('Authorization', access_token) #header中新增token
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req)
result = json.loads(response.read())
print result

get方式的寫法如下:

196b58e3-2c64-eb11-8da9-e4434bdf6706.svgPython

def get_access_token(): 
local_url = 'http://text'
response = urllib2.urlopen(local_url).read()
resp = json.loads(response)
print resp

推薦使用requests庫執行操作更加簡便,操作前請安裝對應庫

POST

196b58e3-2c64-eb11-8da9-e4434bdf6706.svgPython

import requests
data = '{"username":"jack","password":"123"}'
headers = {'Content-Type':'application/json'}
rep = requests.post(url=config['request']['DeleteGraph'], data=data, headers=headers)
return rep.text

GET

196b58e3-2c64-eb11-8da9-e4434bdf6706.svgPython

import requests
url = "https://127.0.0.1/api/"
params = {'username': 'jack', 'password': 'test'}
resp = requests.get(url=url, verify=False, params=params)