python get post類比請求,pythongetpost類比
1.使用get方式時,url類似如下格式:
[html] view plaincopy
- index.jsp?id=100&op=bind
GET報問頭如下:
[html] view plaincopy
- 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] view plaincopy
- 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資料。空行通知伺服器以下不再有要求標頭。
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] view plaincopy
- search=urllib.urlencode({'q':'python'})
輸出為:
[html] view plaincopy
- 'q=python'
7.ok,現在正式開始python的get和post請求:
[html] view plaincopy
- #!/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();
另外通過urllib2
url=/game/user/info?id=28
full_url='http://192.168.1.250'+url.
data=urllib2.urlopen(full_url)
Data=data.read()
python http時使用GET返回成功,使用POST卻返回失敗
你訪問的伺服器返回的post資訊無法識別,可能你的Proxy 伺服器拒絕post頭資訊,你在別的網路試試你的代碼可能不會報錯。你可以在res = con.getresponse()前面添加一句conn.set_debuglevel(1)來看看具體的資訊。
以下來自 documentation for httplib:
exception httplib.BadStatusLine
A subclass of HTTPException.Raisedif a server responds with a HTTP status code that we don’t understand
python 怎接收get 與POST,需要引用什?
import urllib,urllib2
request=urllib2.Request('網址')
response =urllib2.urlopen(request)
對返回的資料操作
POST
post=urllib.urlencode('post資料')
request=urllib2.urlopen('網址',post)
對返回的資料操作