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

问题描述 投票:0回答:4

我有以下代码,我想将其更新到 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())
python python-3.x
4个回答
72
投票
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()

您需要指定请求标头。

>>> 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>'

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 帖子示例


0
投票

conn = http.client.HTTPSConnection("st.auth.itc") conn. 请求( “POST”、“/auth/realms/Staging/protocol/openid-connect/token”、参数、标头) 响应 = conn.getresponse() 打印(响应.状态,响应.原因) 数据=response.read().decode() 返回 JsonResponse(json.loads(data))


-2
投票
conn = http.client.HTTPSConnection('https://api.github.com/markdown')
conn.request("GET", "/markdown")
r1 = conn.getresponse()
print r1.read()
© www.soinside.com 2019 - 2024. All rights reserved.