摘自:http://blog.163.com/xychenbaihu@yeah/blog/static/132229655201231085444250/

测试用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 发送post和get请求的更多相关文章

  1. python发送post和get请求

    python发送post和get请求 get请求: 使用get方式时,请求数据直接放在url中. 方法一. import urllib import urllib2 url = "http: ...

  2. python发送GET或POST请求以便干一些趣事

    适合级别:入门,中级 关键字   :python, http, GET, POST, 安全, 模拟, 浏览器, 验证码,图片识别, google 1 此文不是关于黑客或安全话题的! 2 使用脚本程序发 ...

  3. 用python发送GET和POST请求

    GET请求: python2.7: import urllib,urllib2 url='http://192.168.199.1:8000/mainsugar/loginGET/' textmod ...

  4. Python发送get、post请求

    import json import requests #获取北京天气 # #url= "https://wis.qq.com/weather/common?source=xw&we ...

  5. [原创]利用python发送伪造的ARP请求

    #!/usr/bin/env python import socket s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) s.bind((&qu ...

  6. python用httplib模块发送get和post请求

    在python中,模拟http客户端发送get和post请求,主要用httplib模块的功能. 1.python发送GET请求 我在本地建立一个测试环境,test.php的内容就是输出一句话: 1 e ...

  7. python发送HTTP POST请求

    1. 127.0.0.1和0.0.0.0 127.0.0.1是一个回送地址,指本地机,一般用来本机测试使用,使用127.0.0.1启的服务只能在本地机器上访问,使用0.0.0.0启的服务可以在其他机器 ...

  8. Python接口测试实战2 - 使用Python发送请求

    如有任何学习问题,可以添加作者微信:lockingfree 课程目录 Python接口测试实战1(上)- 接口测试理论 Python接口测试实战1(下)- 接口测试工具的使用 Python接口测试实战 ...

  9. Python发送http请求时遇到问题总结

    1.报错信息为“ERROR 'str' object has no attribute 'endwith'”,排查发现endswith方法名写错了,少了s,写成了 'endwith' if inter ...

随机推荐

  1. Linux Logwatch的学习总结

    Logwatch功能介绍 Logwatch是一款Perl脚本编写的.开源的日志分析工具.它能对原始的日志文件进行解析并转换成结构化格式的文档,也能根据您的使用情况和需求来定制报告.Logwatch的特 ...

  2. 时序数据库InfluxDB安装及使用

    时序数据库InfluxDB安装及使用 1 安装配置 安装 wget https://dl.influxdata.com/influxdb/releases/influxdb-1.3.1.x86_64. ...

  3. Istio入门实战与架构原理——使用Docker Compose搭建Service Mesh

    本文将介绍如何使用Docker Compose搭建Istio.Istio号称支持多种平台(不仅仅Kubernetes).然而,官网上非基于Kubernetes的教程仿佛不是亲儿子,写得非常随便,不仅缺 ...

  4. Java操作Excel(使用POI)

    背景说明 以前写过使用 JXL 操作Excel的例子,但JXL对于Excel 2007版本以后的文件(即扩展名为 .xlsx)无法读取,也找不到可以支持的包.所以,有时不得不用 POI 来操作Exce ...

  5. 【Python 21】52周存钱挑战1.0

    1.案例描述 按照52周存钱法,存钱人必须在一年52周内,每周递存10元.例如,第一周存10元,第二周存20元,第三周存30元,直到第52周存520元. 记录52周后能存多少钱?即10+20+30+. ...

  6. C#基础知识之特性

    一.什么是特性 个人理解:特性本质上也是有一种类,通过添加特性,就可以实例化这个特性类:添加特性就是在类.方法.结构.枚举.组件等上面加一个标签,使这些类.方法.结构.枚举.组件等具有某些统一的特征, ...

  7. SpringBoot前端模板

    Springboot支持thymeleaf.freemarker.JSP,但是官方不建议使用JSP,因为有些功能会受限制,这里介绍thymeleaf和freemarker. 一.thymeleaf模板 ...

  8. Mango 基础知识

    1 mongdb和python交互的模块 pymongo 提供了mongdb和python交互的所有方法 安装方式: pip install pymongo 2 使用pymongo 1. 导入pymo ...

  9. 深入研究EF Core AddDbContext 引起的内存泄露的原因

    前两天逛园子,看到 @Jeffcky 发的这篇文章<EntityFramework Core依赖注入上下文方式不同造成内存泄漏了解一下>. 一开始只是粗略的扫了一遍没仔细看,只是觉得是多次 ...

  10. 即将发布的 ASP.NET Core 2.2 会有哪些新玩意儿?

    今年 6 月份的时候时候 .NET 团队就在 GitHub 公布了 ASP.NET Core 2.2 版本的 Roadmap(文末有链接),而前两天 ASP.NET Core 2.2 预览版 2 已经 ...