python3.x上post發送json資料,python3.xjson

來源:互聯網
上載者:User

python3.x上post發送json資料,python3.xjson

一.摘要

做介面自動化測試時,常常需要使用python發送一些json內容的介面報文,如果使用urlencode對內容進行編碼解析並發送請求,會探索服務器返回了200,OK的狀態,但響應內容不可讀(像是一堆加密報文)。定位問題時發現抓包發現發送報文的內容與我們發送的json內容不符(會去掉”{“與”}“等內容),所以重新採用了json封裝後,問題解決。

二.解決方案

1.先匯入json模組,採用json.dumps將json內容進行封裝

eg:import jsonstr = json.dumps({'userid':'381fccbd776c4deb'})

2.調用這個內容並發送http請求

eg:import http.client,urllib.parseimport jsonstr = json.dumps({'userid':'381fccbd776c4deb'})print(str)#下面注釋部分這樣做是不行的#pararms = urllib.parse.urlencode({'userid':'381fccbd776c4deb'}).encode(encoding='UTF8')headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}conn = http.client.HTTPConnection("10.3.93.216",8080)conn.request('POST', '/ippinte/api/scene/getall', str, headers)response = conn.getresponse()print(response.status, response.reason)data = response.read().decode('utf-8')print(data)conn.close()

附未作json封裝時的結果圖片與封裝成功後的結果圖片:

未作json封裝時的結果圖片

封裝成功後的結果圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.