Using Python to send JSON over HTTP

Source: Internet
Author: User

Because of the need to post some data to the server through the HTTP protocol, so I wrote a small program with Python, did not expect to encounter some problems, so here is the problem to record.


First on the source code:

Import urllib.request
Import json


data = {
' SSID ': ' 123 ',
' passwd ': ' 456 '
}
values = Urllib. Parse.urlencode (data). Encode (encoding= ' UTF8 ')//NOTE 1
headers = {' Content-type ': ' Application/json '}
print ( Data print (values) print (Json.dumps (data)
)
print (Json.dumps (data). Encode ())
request = Urllib.request.Request (url= ' url ', headers=headers, data=json.dumps (data) encode ())
response = Urllib.request.urlopen (Request)



We are using a JSON-formatted request for Python3,post, so:

Import Urllib.request
Import JSON

Headers is the token of JSON

Because

Urllib.request.Request

The data for the post must be bytes format, and Json.dumps is actually converted to STR, so it needs to be. Encode () further converted to bytes for transmission


In addition, note 1 is another way I look up the internet, but I try unsuccessfully. From the output, it changes the dictionary structure and can take a closer look.


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.