前言
最近在使用Python的過程中,發(fā)現(xiàn)網(wǎng)上很少提到在使用post方式時(shí),怎么傳一個(gè)數(shù)組作為參數(shù)的示例,此處根據(jù)自己的實(shí)踐經(jīng)驗(yàn),給出相關(guān)示例,下面話不多說了,來一起跟著小編學(xué)習(xí)學(xué)習(xí)吧。
示例如下:
單純的post請(qǐng)求:
1
|
2
3
4
5
6
7
8
9
10
|
def http_post(): url = " http://152.1.12.11:8080/web " postdata = dict (d = 2 , p = 10 ) post = [] post.append(postdata) req = urllib2.Request(url, json.dumps(post)) #需要是json格式的參數(shù) req.add_header( 'Content-Type' , 'application/json' ) #要非常注意這行代碼的寫法 response = urllib2.urlopen(req) result = json.loads(response.read()) print result |
需要token時(shí)寫法如下:
1
|
2
3
4
5
6
7
8
9
10
11
12
|
def http_post(): url = " http://152.1.12.11:8080/web " 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方式的寫法如下:
1
|
2
3
4
5
|
def get_access_token(): local_url = ' http://152.1.1.1:8080/web ' response = urllib2.urlopen(local_url).read() resp = json.loads(response) print resp |
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)服務(wù)器之家的支持。
原文鏈接:https://segmentfault.com/a/1190000011139585