您的位置:首页技术文章
文章详情页

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

【字号: 日期:2022-08-07 14:58:18浏览:4作者:猪猪
如何解决Python http.client json请求和响应。怎么样??

import http.clientimport jsonconnection = 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>’解决方法

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

我似乎不明白该怎么做。你能帮忙吗?

import urllib2import jsondata = {'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 编程
相关文章: