Python開發【模組】:Requests(二),pythonrequests

來源:互聯網
上載者:User

Python開發【模組】:Requests(二),pythonrequests
Requests模組常見的4中post請求

HTTP 協議規定 POST 提交的資料必須放在訊息主體(entity-body)中,但協議並沒有規定資料必須使用什麼編碼方式。常見的四種編碼方式如下: 

 

1、application/x-www-form-urlencoded 

這應該是最常見的 POST 提交資料的方式了。瀏覽器的原生 form 表單,如果不設定 enctype 屬性,那麼最終就會以 application/x-www-form-urlencoded 方式提交資料。請求類似於下面這樣:

import requestsimport jsonCONFIG = {    'url': 'http://192.168.90.10:8888/',    'headers': {'Content-Type': 'application/x-www-form-urlencoded'}}data = {'content': 'hello',        'digital': '0',        'punctuate': '1',        'engModel': '2'}url = CONFIG['url']headers = CONFIG['headers']response = requests.post(url=url, data=data,headers=headers,timeout=1)print(response.content)

用wirshark進行抓包,分析請求的資料格式

追蹤http資料流,可以看到請求的資料進行了這樣的拼接content=hello&engModel=2&punctuate=1&digital=0

 

2、multipart/form-data 

這又是一個常見的 POST 資料提交的方式。我們使用表單上傳檔案時,必須讓 form 的 enctyped 等於這個值,下面是樣本

import requestsimport jsonCONFIG = {    'url': 'http://192.168.90.10:8888/',    'headers': {'Content-Type': 'multipart/form-data '}}data = {'content': 'hello',        'digital': '0',        'punctuate': '1',        'engModel': '2'}url = CONFIG['url']headers = CONFIG['headers']response = requests.post(url=url, files=data,headers=headers,timeout=1)print(response.content)

用wirshark進行抓包,分析請求的資料格式

 

追蹤http資料流,可以看到請求的資料

 

3、application/json 

application/json 這個 Content-Type 作為回應標頭大家肯定不陌生。實際上,現在越來越多的人把它作為要求標頭,用來告訴服務端訊息主體是序列化後的 JSON 字串。由於 JSON 規範的流行,除了低版本 IE 之外的各大瀏覽器都原生支援 JSON.stringify,服務端語言也都有處理 JSON 的函數,使用 JSON 不會遇上什麼麻煩。

import requestsimport jsonCONFIG = {    'url': 'http://192.168.90.10:8888/',    'headers': {'Content-Type': 'application/json'}}data = {'content': 'hello',        'digital': '0',        'punctuate': '1',        'engModel': '2'}url = CONFIG['url']headers = CONFIG['headers']response = requests.post(url=url, data=json.dumps(data),headers=headers,timeout=1)print(response.content)

用wirshark進行抓包,分析請求的資料格式

追蹤http資料流,可以看到請求的資料

 

 

4、text/xml 

它是一種使用 HTTP 作為傳輸協議,XML 作為編碼方式的遠程調用規範。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.