码迷,mamicode.com
首页 > 编程语言 > 详细

Python向PHP发起GET与POST请求

时间:2014-10-11 13:51:55      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:style   http   io   os   ar   数据   sp   on   cti   


     CloudBean项目中到PHP开发WEB管理端,用Python开发服务控制端,在项目中Python的服务控制端有时候需要主动连接PHP的WEB管理端下载或上传配置参数或数据信息,这里采用的原理是Python模拟Http客户端,向PHP所在的Apache发起Get或Post请求。

     这里将实现的技术代码进行公开。


 一、Python以GET请求的方式,请求PHP页面,并获得返回值

1、python代码:      

<span xmlns="http://www.w3.org/1999/xhtml" style="">[root@AY python]#cat httpclientget.py 
#!/usr/bin/env python
#coding=utf8

import httplib

httpclient=None
print 'bb'
try:
    httpclient=httplib.HTTPConnection('www.xxx.org',80)
    httpclient.request('GET','/CloudBean/capture.php?name=liu&pass=wew')
    res=httpclient.getresponse()
    print res.status
    print res.reason
    print res.read()
except  Exception,e:
    print "heelowr"
</span>

2、php代码:     
<span xmlns="http://www.w3.org/1999/xhtml" style="">[root@AY python]#cat /CloudBean/capture.php 
<?php 
  echo $_GET["name"];
  echo $_GET["pass"];
  echo "GET:";
?>
</span>

二、Python以Post请求的方式,请求PHP页面,并获得返回值

1、Python代码:

<span xmlns="http://www.w3.org/1999/xhtml" style="">[root@AY python]#cat httpclientpost.py 
#!/usr/bin/env python
#coding=utf8

import httplib,urllib

httpclient=None
try:
    params = urllib.urlencode({'name': 'tom', 'pass': 22})
    print 'aaa'
    headers = {"X-CPU": "arm/x86" , "X-USER": "234299044218541","X-RESOLUTION": "240x320","X-SYSTEM":"2.3","X-LANG":"en-us","X-SIGN":"a1ae6bee406a6b8aa0862969ba49cc1d", "X-IMSI":"3110012345678912","X-COUNTRY":"in","X-TIME":"1335339139"}
    httpclient=httplib.HTTPConnection('www.xxx.org',80)
    httpclient.request('POST','/CloudBean/cappost.php',params,headers)
    res=httpclient.getresponse()
    print res.status
    print res.reason
    print res.read()
    print res.getheaders()
except  Exception,e:
    print "error"
</span>
2、PHP代码:

<span xmlns="http://www.w3.org/1999/xhtml" style="">[root@AY python]#cat /CloudBean/cappost.php 
<?php 
  echo $_POST["name"];
  echo $_POST["pass"];
  echo "post";
?>
</span>



Python向PHP发起GET与POST请求

标签:style   http   io   os   ar   数据   sp   on   cti   

原文地址:http://blog.csdn.net/my2005lb/article/details/39992375

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!