當前位置:成語大全網 - 書法字典 - Urllib詞典發布

Urllib詞典發布

本文描述了python通過GET和POST發送http請求和接收http響應的方法。分享給大家供大家參考。

詳情如下:

名為test.py的測試CGI放在apache的cgi-bin目錄中:

#!/usr/bin/python

導入cgi

def main():

打印內容類型:文本/htmln

form = cgi。現場存儲()

if form . has _ key(service code)和form【service code】。值!= :

打印h1妳好,表單【服務代碼】。值,/h1

否則:

打印h1錯誤!請輸入名字。/h1

主()

Python發送post和get請求

獲取請求:

使用get方法時,請求的數據直接放在url中。

方法壹,

導入urllib

導入urllib2

url =

req = urllib2。請求(url)

打印請求

RES _ data = URL lib 2 . URL open(req)

res = res_data.read()

打印分辨率

方法二,

導入httplib

url =

conn = httplib。http connection(192.168.81.16)

conn . request(method = GET,url=url)

response = conn.getresponse()

res= response.read()

打印分辨率

發布請求:

使用post模式時,數據放在數據或正文中,而不是url中,並且在url中將被忽略。

方法壹,

導入urllib

導入urllib2

test_data = {ServiceCode:aaaa,b:bbbbb}

test _ data _ urlencode = urllib . urlencode(test _ data)

請求url =

req = urllib2。請求(url = requrl,data =test_data_urlencode)

打印請求

RES _ data = URL lib 2 . URL open(req)

res = res_data.read()

打印分辨率

方法二,

11

導入urllib

導入httplib

test_data = {ServiceCode:aaaa,b:bbbbb}

test _ data _ urlencode = urllib . urlencode(test _ data)

請求url =

header data = { Host:192.168.81.16 }

conn = httplib。http connection(192.168.81.16)

conn . request(method = POST,url=requrl,body=test_data_urlencode,headers = headerdata)

response = conn.getresponse()

res= response.read()

打印分辨率

python中json的用法不清楚,所以暫時使用urllib . urlencode(test _ data)的方法。

urllib、urllib 2和httplib模塊之間的差異

Httplib實現了http和https的客戶端協議,但在python中,模塊urllib和urllib2在更高的級別上封裝了httplib。

介紹以下示例中使用的函數:

1,HTTPConnection函數

httplib。HTTPConnection(主機【,端口【,靜態【,超時】】】)

這是壹個表示與服務器交互的構造函數,即請求/響應。

主機標識服務器主機(服務器IP或域名)

端口的默認值是80。

Strict模式為False,指示當無法解析服務器返回的狀態行時是否引發BadStatusLine異常。

例如:

conn = http lib . httpconnection(192.168.81.16,80)與服務器建立鏈接。

2.HttpConnection。Request(方法,URL【,正文【,標題】】)函數。

這是對服務器的請求。

方法請求通常是post或get。

例如:

方法=POST或方法=Get。

url請求的資源,請求的資源(頁面或CGI,這裏是CGI)

例如:

url=

或者

url=

body需要提交給服務器的數據可以是json或者上面的格式,json需要調用json模塊。

headers請求的Http標頭數據= { host:192.168.438+0.16 }

例如:

test_data = {ServiceCode:aaaa,b:bbbbb}

test _ data _ urlencode = urllib . urlencode(test _ data)

請求url =

header data = { Host:192.168.81.16 }

conn = httplib。http connection(192.168.81.16,80)

conn . request(method = POST,url=requrl,body=test_data_urlencode,headers = headerdata)

使用後應關閉連接器,連接器。關閉()

3.HTTPConnection.getresponse()函數

這是為了獲取http響應,返回的對象是http response的實例。

4、HTTPResponse簡介:

HTTPResponse的屬性如下:

read(【amt】)獲取響應消息體,AMT表示從響應流中讀取指定字節的數據,如果未指定則讀取所有數據;

get header(name【,default】)獲取響應的標頭,其中name是標頭域名,default用於指定沒有標頭域名時的返回值。

Getheader()獲取列表形式的標題。

例如:

1

2

date=response.getheader(日期);

打印日期

重新頭=

resheder = response . get headers();

打印重新頭

列形式的回應標題信息:

1

2

【(content-length,295),(accept-ranges,bytes),(server,Apache),(last-modified,Sat,31 Mar 2012 10:07:02 GMT),(connection,close),(etag,e8744-127

date=response.getheader(日期);

打印日期

檢索響應標頭中的日期值。

希望這篇文章對妳的Python編程有所幫助。