python的get和post方式请求详解
1.使用get方式时,url类似如下格式:
index.jsp?id=100&op=bind
GET报问头如下:
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报文头如下:
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的编码:
search=urllib.urlencode({'q':'python'})
输出为:
'q=python'
7.ok,现在正式开始python的get和post请求:
#!/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();  
 
 
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号