Python http.client json請(qǐng)求和響應(yīng)。怎么樣?
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())
我會(huì)引導(dǎo)您完成。首先,您需要?jiǎng)?chuàng)建一個(gè)TCP連接,用于與遠(yuǎn)程服務(wù)器進(jìn)行通信。
>>> connection = http.client.HTTPSConnection(’api.github.com’)
-http.client.HTTPSConnection()
然后,您將需要指定請(qǐng)求標(biāo)頭。
>>> headers = {’Content-type’: ’application/json’}
在這種情況下,我們說請(qǐng)求主體的類型為application / json。
接下來,我們將從python dict()生成json數(shù)據(jù)
>>> foo = {’text’: ’Hello world github/linguist#1 **cool**, and #1!’}>>> json_foo = json.dumps(foo)
然后,我們通過HTTPS連接發(fā)送HTTP請(qǐng)求。
>>> connection.request(’POST’, ’/markdown’, json_foo, headers)
獲取響應(yīng)并閱讀。
>>> 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())
相關(guān)文章:
1. jsp實(shí)現(xiàn)登錄驗(yàn)證的過濾器2. jsp+servlet簡單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))3. css代碼優(yōu)化的12個(gè)技巧4. phpstudy apache開啟ssi使用詳解5. jsp EL表達(dá)式詳解6. 解析原生JS getComputedStyle7. xpath簡介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理8. 輕松學(xué)習(xí)XML教程9. jsp cookie+session實(shí)現(xiàn)簡易自動(dòng)登錄10. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法
