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. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)2. Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件列表展示(二)3. 基于PHP做個(gè)圖片防盜鏈4. XML在語音合成中的應(yīng)用5. Jsp servlet驗(yàn)證碼工具類分享6. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)7. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)車輛管理系統(tǒng)8. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)9. asp.net core 認(rèn)證和授權(quán)實(shí)例詳解10. jscript與vbscript 操作XML元素屬性的代碼
