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’}
在這種情況下,我們說(shuō)請(qǐng)求主體的類(lèi)型為application / json。
接下來(lái),我們將從python dict()生成json數(shù)據(jù)
>>> foo = {’text’: ’Hello world github/linguist#1 **cool**, and #1!’}>>> json_foo = json.dumps(foo)
然后,我們通過(guò)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,所需的庫(kù)將更改為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. JavaMail 1.4 發(fā)布2. Intellij IDEA 關(guān)閉和開(kāi)啟自動(dòng)更新的提示?3. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析4. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼5. vue使用webSocket更新實(shí)時(shí)天氣的方法6. 常用數(shù)據(jù)庫(kù)JDBC連接寫(xiě)法(轉(zhuǎn)摘)7. Yii2.0引入CSS,JS文件方法8. Nginx+php配置文件及原理解析9. 你可能真沒(méi)用過(guò)這些 IDEA 插件(建議收藏)10. 淺談python出錯(cuò)時(shí)traceback的解讀
