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())
相關文章: