Post sends json data on python3.x, and python3.xjson

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.