1. 程式人生 > >《跟著小吳哥學python》之 14 Python http請求

《跟著小吳哥學python》之 14 Python http請求

python 模擬get和post請求:

get請求:

import httplib,json
url = "http://192.168.1.162:34343/metrics"
conn = httplib.HTTPConnection("192.168.1.162","34343")
conn.request("GET",url)
response = conn.getresponse()
res= response.read()
obj=json.loads(res)

應用:計算flumechannel中:EventTakeSuccessCount/EventPutSuccessCount比例。

post請求:

import urllib,httplib 
test_data = {'ServiceCode':'aaaa','b':'bbbbb'}
test_data_urlencode = urllib.urlencode(test_data)
requrl = "http://192.168.81.16/cgi-bin/python_test/test.py"
headerdata = {"Host":"192.168.81.16"}
conn = httplib.HTTPConnection("192.168.81.16")
conn.request(method="POST",url=requrl,body=test_data_urlencode,headers = headerdata) 
response = conn.getresponse()
res= response.read()
print res

關於json

import json。 json.loads:把Json格式字串解碼轉換成Python物件。 json.dumps:把一個Python物件編碼轉換成Json字串。