python通过get,post方式发送http请求和接收http响应的方法,pythonget
python通过get,post方式发送http请求和接收http响应的方法,pythonget
本文实例讲述了python通过get,post方式发送http请求和接收http响应的方法。分享给大家供大家参考。具体如下:
测试用CGI,名字为test.py,放在apache的cgi-bin目录下:
#!/usr/bin/python
import cgi
def main():
print "Content-type: text/html\n"
form = cgi.FieldStorage()
if form.has_key("ServiceCode") and form["ServiceCode"].value != "":
print "<h1> Hello",form["ServiceCode"].value,"</h1>"
else:
print "<h1> Error! Please enter first name.</h1>"
main()
python发送post和get请求
get请求:
使用get方式时,请求数据直接放在url中。
方法一、
import urllib
import urllib2
url = "http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"
req = urllib2.Request(url)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res
方法二、
import httplib
url = "http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"
conn = httplib.HTTPConnection("192.168.81.16")
conn.request(method="GET",url=url)
response = conn.getresponse()
res= response.read()
print res
post请求:
使用post方式时,数据放在data或者body中,不能放在url中,放在url中将被忽略。
方法一、
import urllib
import urllib2
test_data = {'ServiceCode':'aaaa','b':'bbbbb'}
test_data_urlencode = urllib.urlencode(test_data)
requrl = "http://192.168.81.16/cgi-bin/python_test/test.py"
req = urllib2.Request(url = requrl,data =test_data_urlencode)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res
方法二、
import urllib
import httplib
test_data = {'ServiceCode':'aaaa','b':'bbbbb'}
test_data_urlencode = urllib.urlencode(test_data)
requrl = "http://192.168.81.16/cgi-bin/python_test/test.py"
headerdata = {"Host":"192.168.81.16"}
conn = httplib.HTTPConnection("192.168.81.16")
conn.request(method="POST",url=requrl,body=test_data_urlencode,headers = headerdata)
response = conn.getresponse()
res= response.read()
print res
对python中json的使用不清楚,所以临时使用了urllib.urlencode(test_data)方法;
模块urllib,urllib2,httplib的区别
httplib实现了http和https的客户端协议,但是在python中,模块urllib和urllib2对httplib进行了更上层的封装。
介绍下例子中用到的函数:
1、HTTPConnection函数
httplib.HTTPConnection(host[,port[,stict[,timeout]]])
这个是构造函数,表示一次与服务器之间的交互,即请求/响应
host 标识服务器主机(服务器IP或域名)
port 默认值是80
strict 模式是False,表示无法解析服务器返回的状态行时,是否抛出BadStatusLine异常
例如:
conn = httplib.HTTPConnection("192.168.81.16",80) 与服务器建立链接。
2、HTTPConnection.request(method,url[,body[,header]])函数
这个是向服务器发送请求
method 请求的方式,一般是post或者get,
例如:
method="POST"或method="Get"
url 请求的资源,请求的资源(页面或者CGI,我们这里是CGI)
例如:
url="http://192.168.81.16/cgi-bin/python_test/test.py" 请求CGI
或者
url="http://192.168.81.16/python_test/test.html" 请求页面
body 需要提交到服务器的数据,可以用json,也可以用上面的格式,json需要调用json模块
headers 请求的http头headerdata = {"Host":"192.168.81.16"}
例如:
test_data = {'ServiceCode':'aaaa','b':'bbbbb'}
test_data_urlencode = urllib.urlencode(test_data)
requrl = "http://192.168.81.16/cgi-bin/python_test/test.py"
headerdata = {"Host":"192.168.81.16"}
conn = httplib.HTTPConnection("192.168.81.16",80)
conn.request(method="POST",url=requrl,body=test_data_urlencode,headers = headerdata)
conn在使用完毕后,应该关闭,conn.close()
3、HTTPConnection.getresponse()函数
这个是获取http响应,返回的对象是HTTPResponse的实例。
4、HTTPResponse介绍:
HTTPResponse的属性如下:
read([amt]) 获取响应消息体,amt表示从响应流中读取指定字节的数据,没有指定时,将全部数据读出;
getheader(name[,default]) 获得响应的header,name是表示头域名,在没有头域名的时候,default用来指定返回值
getheaders() 以列表的形式获得header
例如:
date=response.getheader('date');
print date
resheader=''
resheader=response.getheaders();
print resheader
列形式的响应头部信息:
[('content-length', '295'), ('accept-ranges', 'bytes'), ('server', 'Apache'), ('last-modified', 'Sat, 31 Mar 2012 10:07:02 GMT'), ('connection', 'close'), ('etag', '"e8744-127-4bc871e4fdd80"'), ('date', 'Mon, 03 Sep 2012 10:01:47 GMT'), ('content-type', 'text/html')]
date=response.getheader('date');
print date
取出响应头部的date的值。
python通过get,post方式发送http请求和接收http响应的方法,pythonget的更多相关文章
- python通过get方式,post方式发送http请求和接收http响应-urllib urllib2
python通过get方式,post方式发送http请求和接收http响应-- import urllib模块,urllib2模块, httplib模块 http://blog.163.com/xyc ...
- 在android用Get方式发送http请求
烦人的日子终于过去啦,终于又可以写博客啦,对自己的android学习做个总结,方便以后查看...... 一.在android用Get方式发送http请求,使用的是java标准类,也比较简单. 主要分以 ...
- WebClient以POST方式发送Web请求
本例使用WebClient以POST方式发送Web请求并下载一个文件,难点是postData的构造,发送Web请求时有的网站要求可能要求 Cookies前后一致.其中application/x-www ...
- AJAX方式发送远程请求报错:No 'Access-Control-Allow-Origin' header
AJAX GET方式发送远程请求,chrome开发者工具console中报错:XMLHttpRequest cannot load http://www.shikezhi.com/ajax/getDa ...
- 安卓基础之Get方式发送http请求
本文参考作者:超超boy 链接:https://www.cnblogs.com/jycboy/p/post01.html 一.在android用Get方式发送http请求,使用的是java标准类. 主 ...
- python+pytest接口自动化(5)-发送post请求
简介 在HTTP协议中,与get请求把请求参数直接放在url中不同,post请求的请求数据需通过消息主体(request body)中传递. 且协议中并没有规定post请求的请求数据必须使用什么样的编 ...
- python测试开发django-50.jquery发送ajax请求(get)
前言 有时候,我们希望点击页面上的某个按钮后,不刷新整个页面,给后台发送一个请求过去,请求到数据后填充到html上,这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新.Ajax可以完美的 ...
- python接口自动化二(发送post请求)
前言 一个http请求包括三个部分,为别为请求行,请求报头,消息主体,类似以下这样: 请求行 请求报头 消息主体 HTTP协议规定post提交的数据必须放在消息主体中,但是协议并没有规定必须使用什么编 ...
- Python接口测试-使用requests模块发送GET请求
本篇主要记录下使用python的requests模块发送GET请求的实现代码. 向服务器发送get请求:无参数时:r = requests.get(url)带params时:r = requests. ...
随机推荐
- JAVA中String类常用方法 I
String类常用方法有: int length() -– 返回当前字符串的长度 int indexOf(int ch) -– 查找ch字符在该字符串中第一次出现的位置 int indexOf(Str ...
- 前端框架React Js入门教程【精】
现在最热门的前端框架有AngularJS.React.Bootstrap等.自从接触了ReactJS,ReactJs的虚拟DOM(Virtual DOM)和组件化的开发深深的吸引了我,下面来跟我一起领 ...
- Ubuntu16.04上使用Anaconda3的Python3.6的pip安装UWSGI报错解决办法
具体报错信息: lto1: fatal error: bytecode stream generated with LTO version 6.0 instead of the expected 4. ...
- windows 系统中的 afd 驱动
afd 的全称是 Ancillary Function Driver for WinSock,是 windows 系统网络部分的核心工具.同 Linux 类似,windows 的 socket 最终也 ...
- 什么是同源策略,什么是跨域,如何跨域,Jsonp/CORS跨域
同源策略 同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响. 可以说Web是构建在同源策略基础之上 ...
- 【Windows】创建任务计划
任务计划,可以将任何脚本.程序或文档安排在某个时间运行. 可以按照如下的方式来启动:附件 -> 系统工具 -> 任务计划程序. 也可以在Win+R后,输入:taskschd.msc 命令来 ...
- CorelCAD for Mac(绘图设计软件)破解版安装
1.软件简介 CorelCAD 是 macOS 系统上的 CAD 绘图工具,为我们提供了获取本地 DWG 格式的高性能 CAD 设计解决方案.打开.处理和保存 .DWG 文件,实现轻松协作.借助 ...
- [Aaronyang] 写给自己的WPF4.5 笔记17[Page实现页面导航]
1. 第一个Page页使用 新建PageDemo解决方案,默认wpf应用程序 右键项目新建页,然后指定App.xaml的默认启动窗口,为Page1.xaml,F5运行项目 文章内容已经迁移http:/ ...
- 关于tcp中time_wait状态的4个问题
time_wait是个常问的问题.tcp网络编程中最不easy理解的也是它的time_wait状态,这也说明了tcp/ip四次挥手中time_wait状态的重要性. 以下通过4个问题来描写叙述它 问题 ...
- Android 组件系列-----Activity生命周期
本篇随笔将会深入学习Activity,包括如何定义多个Activity,并设置为默认的Activity.如何从一个Activity跳转到另一个Activity,还有就是详细分析Activity的生命周 ...