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())
相关文章:
1. Python unittest生成测试报告过程解析2. php去掉数组的第一个值的两个函数:array_shift、array_splice3. python matplotlib工具栏源码探析二之添加、删除内置工具项的案例4. CSS Hack大全-教你如何区分出IE6-IE10、FireFox、Chrome、Opera5. CSS3实例分享之多重背景的实现(Multiple backgrounds)6. Django-simple-captcha验证码包使用方法详解7. 用PHP读取和编写XML DOM8. uni-app结合PHP实现单用户登陆demo及解析9. 如何基于python3和Vue实现AES数据加密10. 解决VUE项目使用Element-ui 下拉组件的验证失效问题

网公网安备