Python http.client json请求和响应.怎么样?

ASP*_*iRE 15 python python-3.x

我有以下代码,我想更新到Python 3.x所需的库将更改为http.client和json.

我似乎无法理解如何做到这一点.你能帮忙吗?

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())
Run Code Online (Sandbox Code Playgroud)

joa*_*oar 32

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())
Run Code Online (Sandbox Code Playgroud)

我会引导你完成它.首先,您需要创建一个TCP连接,用于与远程服务器通信.

>>> connection = http.client.HTTPSConnection('api.github.com')
Run Code Online (Sandbox Code Playgroud)

- http.client.HTTPSConnection()

您需要指定请求标头.

>>> headers = {'Content-type': 'application/json'}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我们说请求主体是application/json类型.

接下来我们将从python dict()生成json数据

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

然后我们通过HTTPS连接发送HTTP请求.

>>> connection.request('POST', '/markdown', json_foo, headers)
Run Code Online (Sandbox Code Playgroud)

得到回复并阅读.

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