python 傳送http請求

2021-06-23 04:52:13 字數 3969 閱讀 5332

測試用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 "" 

else:   

print "" 

main()

python傳送post和get請求

get請求:

使用get方式時,請求資料直接放在url中。

方法一、

import urllib

import urllib2

url = ""

req = urllib2.request(url)

print req

res_data = urllib2.urlopen(req)

res = res_data.read()

print res

方法二、

post請求:

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

方法一、

import urllib

import urllib2

test_data =

test_data_urlencode = urllib.urlencode(test_data)

requrl = ""

req = urllib2.request(url = requrl,data =test_data_urlencode)

print req

res_data = urllib2.urlopen(req)

res = res_data.read()

print res

方法二、

對python中json的使用不清楚,所以臨時使用了urllib.urlencode(test_data)方法;

模組urllib,urllib2,httplib的區別

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

介紹下例子中用到的函式:

1、httpconnection函式

這個是建構函式,表示一次與伺服器之間的互動,即請求/響應

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=""      請求cgi

或者url=""                請求頁面

body               需要提交到伺服器的資料,可以用json,也可以用上面的格式,json需要呼叫json模組

headers         請求的http頭headerdata =

例如:test_data =

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的值。

PHP 傳送HTTP請求

file get contents版本 傳送post請求 param string url 請求位址 param array post data post鍵值對資料 return string function send post url,post data 使用如下 post data array...

後台傳送Http請求

get方式傳送請求 建立http請求 指定請求型別 接收伺服器響應結果 post傳送請求 傳送請求 指定請求型別 將要post給伺服器的資料寫入請求建立的流中 接收伺服器響應結果 httpwebrequest不能直接通過new來建立,只能通過webrequest.create url 的方式來獲得。...

java傳送http請求

方法一 1.現將要傳輸的引數轉化為json格式 比如將物件轉為json格式 jsonobject jsonobj jsonobject.fromobject data 2.拼裝url string url url?data jsonobj 3.呼叫以下方法 return json.tostring ...