Post sends json data on python3.x, and python3.xjson
I. Summary
During API automated testing, you often need to use python to send some interface messages with json content. If you use urlencode to parse the content and send a request, the server returns 200, OK status, but the response content is not readable (like a bunch of encrypted packets ). When locating the problem, we found that packet capture found that the content of the sent message is inconsistent with the json content we sent ("{" and "}" will be removed), so after the json encapsulation is adopted again, solve the problem.
Ii. Solution
1. Import the json module first and use json. dumps to encapsulate json content
eg:import jsonstr = json.dumps({'userid':'381fccbd776c4deb'})
2. Call this content and send an http request
Eg: import http. client, urllib. parseimport jsonstr = json. dumps ({'userid': '381fccbd776c4deb'}) print (str) # The following comments do not work. # 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 ()
The result image is not encapsulated in json format or the result image is successfully encapsulated:
Result image when json encapsulation is not performed
Result image after successful Encapsulation