python编程中得get和post请求

作者: shaneZhang 分类: 互联网技术 发布时间: 2015-08-20 13:19

前提

测试用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 " Hello",form["ServiceCode"].value,"" 
    else:   
        print " Error! Please enter first name." 
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编程中得get和post请求

如果觉得我的文章对您有用,请随意打赏。如果有其他问题请联系博主QQ(909491009)或者下方留言!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注