简体   繁体   中英

Python http.client json request and response. How?

I have the following code that I'd like to update to Python 3.x The required libraries would change to http.client and json.

I can't seem to understand how to do it. Can you please help?

import urllib2
import json


data = {"text": "Hello world github/linguist#1 **cool**, and #1!"}
json_data = json.dumps(data)

req = urllib2.Request("https://api.github.com/markdown")
result = urllib2.urlopen(req, json_data)

print '\n'.join(result.readlines())
import http.client
import json

connection = http.client.HTTPSConnection('api.github.com')

headers = {'Content-type': 'application/json'}

foo = {'text': 'Hello world github/linguist#1 **cool**, and #1!'}
json_foo = json.dumps(foo)

connection.request('POST', '/markdown', json_foo, headers)

response = connection.getresponse()
print(response.read().decode())

I will walk you through it. First you'll need to create a TCP connection that you will use to communicate with the remote server.

>>> connection = http.client.HTTPSConnection('api.github.com')

-- http.client.HTTPSConnection()

Thẹ̣n you will need to specify the request headers.

>>> headers = {'Content-type': 'application/json'}

In this case we're saying that the request body is of the type application/json.

Next we will generate the json data from a python dict()

>>> foo = {'text': 'Hello world github/linguist#1 **cool**, and #1!'}
>>> json_foo = json.dumps(foo)

Then we send an HTTP request to over the HTTPS connection.

>>> connection.request('POST', '/markdown', json_foo, headers)

Get the response and read it.

>>> response = connection.getresponse()
>>> response.read()
b'<p>Hello world github/linguist#1 <strong>cool</strong>, and #1!</p>'

To make your code Python 3 compatible it is enough to change import statements and encode/decode data assuming utf-8 everywhere:

import json
from urllib.request import urlopen

data = {"text": "Hello world github/linguist№1 **cool**, and #1!"}
response = urlopen("https://api.github.com/markdown", json.dumps(data).encode())
print(response.read().decode())

See another https post example .

conn = http.client.HTTPSConnection('https://api.github.com/markdown')
conn.request("GET", "/markdown")
r1 = conn.getresponse()
print r1.read()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM