python http請求post參數,json解析

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);
}
?>


測試結果:


發佈了37 篇原創文章 · 獲贊 3 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章