python通過get方式,post方式發送http請求和接收http響應-urllib urllib2

來源:互聯網
上載者:User
python通過get方式,post方式發送http請求和接收http響應-- import urllib模組,urllib2模組, httplib模組  

http://blog.163.com/xychenbaihu@yeah/blog/static/132229655201231085444250/

測試用CGI,名字為test.py,放在apache的cgi-bin目錄下:
#!/usr/bin/python
import cgi
def main():
    print "Content-type: text/html\n"
    form = cgi.FieldStorage()
    if form.has_key("ServiceCode") and form["ServiceCode"].value != "":
        print "<h1> Hello",form["ServiceCode"].value,"</h1>"
    else:  
        print "<h1> Error! Please enter first name.</h1>"
main()

 

python發送post和get請求

get請求:

使用get方式時,請求資料直接放在url中。
方法一、
import urllib
import urllib2

url = "http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"

req = urllib2.Request(url)
print req

res_data = urllib2.urlopen(req)
res = res_data.read()
print res

方法二、
import httplib

url = "http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"

conn = httplib.HTTPConnection("192.168.81.16")
conn.request(method="GET",url=url) 

response = conn.getresponse()
res= response.read()
print res

post請求:

使用post方式時,資料放在data或者body中,不能放在url中,放在url中將被忽略。
方法一、
import urllib
import urllib2

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"

req = urllib2.Request(url = requrl,data =test_data_urlencode)
print req

res_data = urllib2.urlopen(req)
res = res_data.read()
print res


方法二、
import urllib
import 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
對python中json的使用不清楚,所以臨時使用了urllib.urlencode(test_data)方法;

 

模組urllib,urllib2,httplib的區別
        httplib實現了http和https的用戶端協議,但是在python中,模組urllib和urllib2對httplib進行了更上層的封裝。
 

介紹下例子中用到的函數:
1、HTTPConnection函數

httplib.HTTPConnection(host[,port[,stict[,timeout]]])
這個是建構函式,表示一次與伺服器之間的互動,即請求/響應
host        識別服務器主機(伺服器IP或網域名稱)
port         預設值是80
strict        模式是False,表示無法解析伺服器返回的狀態行時,是否拋出BadStatusLine異常
例如:
         conn = httplib.HTTPConnection("192.168.81.16",80)          與伺服器建立連結。

 
2、HTTPConnection.request(method,url[,body[,header]])函數
這個是向伺服器發送請求
method           請求的方式,一般是post或者get,

例如:

         method="POST"或method="Get"
url                  請求的資源,請求的資源(頁面或者CGI,我們這裡是CGI)

例如:

        url="http://192.168.81.16/cgi-bin/python_test/test.py"      請求CGI

        或者

        url="http://192.168.81.16/python_test/test.html"                請求頁面
body               需要提交到伺服器的資料,可以用json,也可以用上面的格式,json需要調用json模組
headers         請求的http頭headerdata = {"Host":"192.168.81.16"}
例如:
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",80)
conn.request(method="POST",url=requrl,body=test_data_urlencode,headers = headerdata) 
conn在使用完畢後,應該關閉,conn.close()


3、HTTPConnection.getresponse()函數
     這個是擷取http響應,返回的對象是HTTPResponse的執行個體。

 


4、HTTPResponse介紹:
HTTPResponse的屬性如下:
read([amt])                              擷取響應訊息體,amt表示從響應流中讀取指定位元組的資料,沒有指定時,將全部資料讀出;
getheader(name[,default])      獲得響應的header,name是表示頭網域名稱,在沒有頭網域名稱的時候,default用來指定傳回值
getheaders()                           以列表的形式獲得header
例如:

date=response.getheader('date');
print date
resheader=''
resheader=response.getheaders();
print resheader

列形式的回應標頭部資訊:

[('content-length', '295'), ('accept-ranges', 'bytes'), ('server', 'Apache'), ('last-modified', 'Sat, 31 Mar 2012 10:07:02 GMT'), ('connection', 'close'), ('etag', '"e8744-127-4bc871e4fdd80"'), ('date', 'Mon, 03 Sep 2012 10:01:47 GMT'), ('content-type', 'text/html')] 

date=response.getheader('date');
print date

取出回應標頭部的date的值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.