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的更多相关文章

  1. python通过get方式,post方式发送http请求和接收http响应-urllib urllib2

    python通过get方式,post方式发送http请求和接收http响应-- import urllib模块,urllib2模块, httplib模块 http://blog.163.com/xyc ...

  2. 在android用Get方式发送http请求

    烦人的日子终于过去啦,终于又可以写博客啦,对自己的android学习做个总结,方便以后查看...... 一.在android用Get方式发送http请求,使用的是java标准类,也比较简单. 主要分以 ...

  3. WebClient以POST方式发送Web请求

    本例使用WebClient以POST方式发送Web请求并下载一个文件,难点是postData的构造,发送Web请求时有的网站要求可能要求 Cookies前后一致.其中application/x-www ...

  4. AJAX方式发送远程请求报错:No 'Access-Control-Allow-Origin' header

    AJAX GET方式发送远程请求,chrome开发者工具console中报错:XMLHttpRequest cannot load http://www.shikezhi.com/ajax/getDa ...

  5. 安卓基础之Get方式发送http请求

    本文参考作者:超超boy 链接:https://www.cnblogs.com/jycboy/p/post01.html 一.在android用Get方式发送http请求,使用的是java标准类. 主 ...

  6. python+pytest接口自动化(5)-发送post请求

    简介 在HTTP协议中,与get请求把请求参数直接放在url中不同,post请求的请求数据需通过消息主体(request body)中传递. 且协议中并没有规定post请求的请求数据必须使用什么样的编 ...

  7. python测试开发django-50.jquery发送ajax请求(get)

    前言 有时候,我们希望点击页面上的某个按钮后,不刷新整个页面,给后台发送一个请求过去,请求到数据后填充到html上,这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新.Ajax可以完美的 ...

  8. python接口自动化二(发送post请求)

    前言 一个http请求包括三个部分,为别为请求行,请求报头,消息主体,类似以下这样: 请求行 请求报头 消息主体 HTTP协议规定post提交的数据必须放在消息主体中,但是协议并没有规定必须使用什么编 ...

  9. Python接口测试-使用requests模块发送GET请求

    本篇主要记录下使用python的requests模块发送GET请求的实现代码. 向服务器发送get请求:无参数时:r = requests.get(url)带params时:r = requests. ...

随机推荐

  1. 使用 IntraWeb (28) - 基本控件之 TIWTemplateProcessorHTML、TIWLayoutMgrHTML、TIWLayoutMgrForm

    TIWTemplateProcessorHTML //使用外部的 html 文件做模板 TIWLayoutMgrHTML //直接输入 Html 文本做模板 TIWLayoutMgrForm //这应 ...

  2. GO开发环境搭建

    GO开发环境搭建 1)下载GO SDK,并安装 https://golang.google.cn/dl/ 2)下载GO IDE:GOLAND,并安装 3)设置GOROOT和GOPATH 4)新建一个工 ...

  3. Windows2003配置集群详解

    原文: http://blog.csdn.net/xunyn/article/details/7388900 集群是在一组计算机上运行相同的软件并虚拟成一台主机系统为客户端与应用提供服务:计算机通过缆 ...

  4. 9.5 dubbo事件通知机制

    dubbo事件通知机制:http://dubbo.io/books/dubbo-user-book/demos/events-notify.html 一.使用方式 两个服务: DemoService: ...

  5. boost.xml_parser中文字符问题 (转)

    当使用xml_parser进行读xml时,如果遇到中文字符会出现解析错误. 网上有解决方案说使用wptree来实现,但当使用wptree来写xml时也会出错.而使用ptree来写中文时不会出错. 综合 ...

  6. 版本控制-搭建git服务器

    GitHub是一个免费托管开源代码的Git服务器,如果我们不想公开项目的源代码,又不想付费使用,那么我们可以自己搭建一台Git服务器. 下面我们就看看,如何在Ubuntu上搭建Git服务器.我们使用V ...

  7. [Unit Testing] Using Mockito Annotations - @Mock, @InjectMocks, @RunWith

    Previously we have seen how to do Unit testing with Mockito; import org.junit.Test; import static or ...

  8. fiddler展示serverIP方法

    转载自:http://www.xuanfengge.com/fiddler-displays-the-set-ip-method.html 前言 由于web前端在多个环境中开发,需要经常更换host, ...

  9. 【SqlServer】解析SqlServer的分页

    方式1: 假设页数是10,现在要拿出第5页的内容,查询语句如下: --10代表分页的大小 * from test where id not in ( --40是这么计算出来的:10*(5-1) id ...

  10. 12C配置EM Express的https端口

    1.启动监听并查看监听信息 $ lsnrctl stat ora12 LSNRCTL for Linux: Version 12.1.0.2.0 - Production on 07-FEB-2017 ...