python發送post請求

來源:互聯網
上載者:User
#!/usr/bin/python
02 #-*-coding:utf-8-*-
03    
04 import httplib,urllib;  #載入模組
05   
06 #定義需要進行發送的資料
07 params = urllib.urlencode({'title':'標題','content':'文章'});
08 #定義一些檔案頭
09 headers = {"Content-Type":"application/x-www-form-urlencoded",
10            "Connection":"Keep-Alive","Referer":"http://mod.qlj.sh.cn/sing/post.php"};
11 #與網站構建一個串連
12 conn = httplib.HTTPConnection("http://mod.qlj.sh.cn/sing/");
13 #開始進行資料提交   同時也可以使用get進行
14 conn.request(method="POST",url="post.php",body=params,headers=headers);
15 #返回處理後的資料
16 response = conn.getresponse();
17 #判斷是否提交成功
18 if response.status == 302:
19     print "發布成功!";
20 else:
21     print "發布失敗";
22 #關閉串連
23 conn.close();<span id="more-998"></span>

不使用COOKIES 簡單提交

1 import urllib2, urllib
2   
3 data = {'name' : 'www', 'password' : '123456'}
4 f = urllib2.urlopen(
5         url     = 'http://www.ideawu.net/',
6         data    = urllib.urlencode(data)
7         )
8 print f.read()

使用COOKIES 複雜

01 import urllib2 
02 cookies = urllib2.HTTPCookieProcessor()
03 opener = urllib2.build_opener(cookies)
04   
05 f = opener.open('http://www.ideawu.net/?act=login&name=user01')
06   
07 data = '<root>Hello</root>'
08 request = urllib2.Request(
09         url     = 'http://www.ideawu.net/?act=send',
10         headers = {'Content-Type' : 'text/xml'},
11         data    = data)
12   
13 opener.open(request)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.