1.使用get方式時,url類似如下格式:
[html]
index.jsp?id=100&op=bind
GET報問頭如下:
[html]
GET /sn/index.php?sn=123&n=asa HTTP/1.1
Accept: */*
Accept-Language: zh-cn
host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: 12
Connection:close
2.使用post方式時,POST方法將請求參數封裝在HTTP請求數據中,以名稱/值的形式出現,可以傳輸大量數據,可用來傳送文件。
POST報文頭如下:
[html]
POST /sn/index.php HTTP/1.1
Accept: */*
Accept-Language: zh-cn
host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: 12
Connection:close
sn=123&n=asa
在http頭後邊有一空行,空行後邊接着發送post數據在http頭後邊有一空行,空行後邊接着發送post數據在http頭後邊有一空行,空行後邊接着發送post數據在http頭後邊有一空行,空行後邊接着發送post數據。空行通知服務器以下不再有請求頭。
3.可以發現的一點是,無論是post還是get方式,他們所傳遞的數據都要進行url編碼
4. url編碼是一種瀏覽器用來打包表單輸入的格式。
瀏覽器從表單中獲取所有的name和其中的值 ,將它們以name/value參數編碼(移去那些不能傳送的字符,將數據排行等等)作爲URL的一部分或者分離地發給服務器。
不管哪種情況,在服務器端的表單輸入格式樣子象這樣:
theName=Ichabod+Crane&gender=male&status=missing& ;headless=yes
5.URL編碼遵循下列規則:
1.每對name/value由&;符分開;
2.每對來自表單的name/value由=符分開。
3.如果用戶沒有輸入值給這個name,那麼這個name還是出現,只是無值。
4.任何特殊的字符(就是那些不是簡單的七位ASCII,如漢字)將以百分符%用十六進制編碼,
6.所以,當我們使用get或者post傳送數據之前,我們都需要對數據進行url編碼。
urllib庫提供了一個函數來實現url的編碼:
[html]
search=urllib.urlencode({'q':'python'})
輸出爲:
[html]
'q=python'
7.ok,現在正式開始python的get和post請求:
[html]
#!/usr/bin/python
#-*-coding:utf-8-*-
# 進行表單提交 小項 2008-10-09
import httplib,urllib; #加載模塊
#定義需要進行發送的數據
params = urllib.urlencode({'cat_id':'6',
'news_title':'標題-Test39875',
'news_author':'Mobedu',
'news_ahome':'來源',
'tjuser':'carchanging',
'news_keyword':'|',
'news_content':'測試-Content',
'action':'newnew',
'MM_insert':'true'});
#定義一些文件頭
headers = {"Content-Type":"application/x-www-form-urlencoded",
"Connection":"Keep-Alive","Referer":"http://192.168.1.212/newsadd.asp?action=newnew"};
#與網站構建一個連接
conn = httplib.HTTPConnection("192.168.1.212");
#開始進行數據提交 同時也可以使用get進行
conn.request(method="POST",url="/newsadd.asp?action=newnew",body=params,headers=headers);
#返回處理後的數據
response = conn.getresponse();
#判斷是否提交成功
if response.status == 302:
print "發佈成功!^_^!";
else:
print "發佈失敗\^0^/";
#關閉連接
conn.close();