29

我有以下代码要更新到 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())
4

3 回答 3

60
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())

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

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

--http.client.HTTPSConnection()

Thẹ̣n 您将需要指定请求标头。

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

在这种情况下,我们说请求正文的类型为 application/json。

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

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

然后我们通过 HTTPS 连接发送一个 HTTP 请求。

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

得到响应并阅读它。

>>> response = connection.getresponse()
>>> response.read()
b'<p>Hello world github/linguist#1 <strong>cool</strong>, and #1!</p>'
于 2012-08-01T17:12:03.180 回答
1

为了使您的代码与 Python 3 兼容,更改导入语句和编码/解码数据就足够了,假设utf-8无处不在:

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())

请参阅另一个 https 帖子示例

于 2012-08-01T18:30:03.307 回答
0
conn = http.client.HTTPSConnection('https://api.github.com/markdown')
conn.request("GET", "/markdown")
r1 = conn.getresponse()
print r1.read()
于 2012-08-01T16:57:25.933 回答