您的位置:首页 > 理论基础 > 计算机网络

python http请求post参数,json解析

2014-06-09 17:57 811 查看
python的访问网络太简单了

下面是python的测测试 代码

# -*- coding: utf-8 -*-
import sys,json
import urllib,urllib2
uri = 'http://localhost/test_post_get.php'
params = {
'_c': 'user',#post参数有两种写法
'_m': 'info',
};
print sys.getdefaultencoding()
params['dotype']= 1
params['username'] = '全仔'
params = urllib.urlencode(params)
ret = urllib.urlopen(uri, params)
code = ret.getcode()
print code #状态码
ret_data = ret.read()
print ret_data.decode('utf-8')
print json.dumps(ret_data)
dic = json.loads(ret_data)
print dic
print dic['username']
附上服务端的PHP代码:(随便写的。。。。)

<?php
$from_py_username = $_POST['username'];
$dotype = $_POST['dotype'];
$u = $_POST['_c'];
if($dotype == 0)
{
$res =
array(
"id"=> rand(0,100),
"username"=>$from_py_username,
"time"=>time(),
"dotype"=>$dotype,
"code"=>100
);
echo JSON($res);
}else if($dotype == 1)
{
$res =
array(
"id"=> rand(0,100),
"username"=>$from_py_username,
"time"=>time(),
"dotype"=>$dotype,
"c"=>$u,
"code"=>100
);
echo JSON($res);
}else
{
$res =
array(
"id"=> rand(0,100),
"username"=>$from_py_username,
"time"=>time(),
"code"=>101
);
echo JSON($res);
}

function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
foreach ($array as $key => $value) {
if (is_array($value)) {

arrayRecursive($array[$key], $function, $apply_to_keys_also);
} else {
$array[$key] = $function($value);
}

if ($apply_to_keys_also && is_string($key)) {
$new_key = $function($key);
if ($new_key != $key) {
$array[$new_key] = $array[$key];
unset($array[$key]);
}
}
}
}
function JSON($array) {
arrayRecursive($array, 'urlencode', true);
$json = json_encode($array);
return urldecode($json);
}
?>


测试结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: