1. 程式人生 > >python之介面請求

python之介面請求

      實際工作中,需要用到python來對伺服器進行請求(也是方便進行介面自動化),因為,本文來記錄一下python是如何來進行get和post請求的,本文針對python的httplib模組介紹get和post請求,urllib模組直接進行請求

1、httplib模組之get請求,直接上程式碼。

#coding=utf-8
import httplib,urllib
import json

httpClient=None
try:
   httpClient=httplib.HTTPConnection('test.web.com',80,timeout=30)#注意,此處域名不要帶http://
   headers={'Accept':'application/json','cookie':'PHPSESSID=xxxxx'}#如果有headers的話就帶上。沒有則不用
   httpClient.request(method='GET',url='/main/?r=get/student',headers=headers)
   response=httpClient.getresponse()
   data=json.load(response,encoding='utf-8')#將獲取到的內容轉換為json型別資料
except Exception,e:
    raise e
finally:
   if httpClient:
   	   httpClient.close()


2、httplib模組之post請求,直接上程式碼
#coding=utf-8
import httplib,urllib
import json

httpClient=None
try:
   httpClient=httplib.HTTPConnection('test.web.com',80,timeout=30)#注意,此處域名不要帶http://
   headers={'Content-type':'application/x-www-form-urlcoded','Accept':'text/plain','cookie':'PHPSESSID=xxxxx'}#post請求頭需要有content-type,否則失敗
   #嘗試過,不知道為啥。。
   params=urllib.urlencode({"ID:292})#post的引數,這裡需要是一個物件的形式
   httpClient.request('POST','/main/?r=get/student',params,headers)#這裡可以不帶key,直接用value
   response=httpClient.getresponse()
   data=json.load(response,encoding='utf-8')#將獲取到的內容轉換為json型別資料
   print "name=%s"%(data['name'])#直接讀取
except Exception,e:
   raise e
finally:
   if httpClient:
      httpClient.close()

3、python另有一種請求介面的方法,就是用urllib的urlopen方法直接請求,用法如下
response=urllib.urlopen('http://test.web.com/main/?r=get/student&ID=%s'%(stu_id))#id自己定義