当前位置:首页 > Python >

python发送post请求

发布时间:2016-01-23 15:58:20 作者:佚名 阅读:(1463)

Python发送post请求实例代码

#!/usr/bin/python
#-*-coding:utf-8-*-
  
import httplib,urllib;  #加载模块
 
#定义需要进行发送的数据
params = urllib.urlencode({'title':'标题','content':'文章'});
#定义一些文件头
headers = {"Content-Type":"application/x-www-form-urlencoded",
           "Connection":"Keep-Alive","Referer":"https://www.itbiancheng.com/sing/post.php"};
#与网站构建一个连接
conn = httplib.HTTPConnection("https://www.itbiancheng.com/sing/");
#开始进行数据提交   同时也可以使用get进行
conn.request(method="POST",url="post.php",body=params,headers=headers);
#返回处理后的数据
response = conn.getresponse();
#判断是否提交成功
if response.status == 302:
    print "发布成功!";
else:
    print "发布失败";
#关闭连接
conn.close();<span id="more-998"></span>
不使用COOKIES 简单提交

import urllib2, urllib
&nbsp;
data = {'name' : 'www', 'password' : '123456'}
f = urllib2.urlopen(
        url     = 'https://www.itbiancheng.com/',
        data    = urllib.urlencode(data)
        )
print f.read()
使用COOKIES 复杂

import urllib2&nbsp;
cookies = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookies)
&nbsp;
f = opener.open('https://www.itbiancheng.com/?act=login&name=user01')
&nbsp;
data = '<root>Hello</root>'
request = urllib2.Request(
        url     = 'https://www.itbiancheng.com/?act=send',
        headers = {'Content-Type' : 'text/xml'},
        data    = data)
&nbsp;
opener.open(request)

欢迎分享转载→ python发送post请求

© 2015-2019 - 吾爱编程网 版权所有 苏ICP备18033726号-1关于我们 - 网站声明 - 联系我们