NodeMCU教程 http.get請求及上傳中文亂碼解決方案
這是練英語寫作的,中文在下面。
1、Connect Wifi
Before we make a http-get request, connecting Wifi must be done.The demo gave by official website is as Code Block-1. See http://nodemcu.com/index_cn.html
2、PHP Webserver
By using php,we can get the request arguments by _GET['xxx'] directly. Demo is as Code Block-2.
3、NodeMcu Request
Demo is as Code Block-3. We used the cjson module to parse the Json data returned by php server and iterate over and print the elements.
4、Chinise Garbled Solution
Since the url of NodeMcu http-get request supports Chinise badly,we can use the Base64 encoded url. For example, the base64 code of '你好' is '5L2g5aW9Cg==', then the url will be 'login.php?name=5L2g5aW9Cg=='. The php server should decode the data such as the Code Block-4.
—————————————————————————————————————————
上面是練英語寫作的,歡迎吐槽。中文如下:
1、連線 Wifi
在進行Http 的GET請求前,我們需要連線Wifi.官方給出了一個例子,程式碼如下
連線Wifi程式碼Code Block-1:
print(wifi.sta.getip())
--nil
wifi.setmode(wifi.STATION)
wifi.sta.config("SSID","password")
print(wifi.sta.getip())
--192.168.18.110
參考
http://nodemcu.com/index_cn.html2、PHP服務端
PHP服務端通過_GET['xxx']即可獲取到GET請求引數。程式碼如下:
PHP服務端程式碼Code Block-2:
<?php
$user_name = isset($_GET['name'])?$_GET['name']:null;
$user_pwd = isset($_GET['pwd'])?$_GET['pwd']:null;
$message = array(
"type" => 0,
"data" => "name:".$user_name." pwd:".$user_pwd
);
echo json_encode($message);
?>
3、NodeMCU請求
程式碼如下,我們通過cjson模組來解析PHP服務端返回的Json資料並且遍歷輸出。
NodeMcu進行php.get請求程式碼Code Block-2:
http.get("http://192.168.1.106/login.php?name=aa&pwd=11", nil, function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code,data)
t = cjson.decode(data)
for k,v in pairs(t) do print(k,v) end
end
end)
4、中文引數亂碼解決
NodeMCU對GET請求的URL引數中文支援並不好,我們可以使用Base64編碼後的引數。比如說"你好"的base64編碼為 ”5L2g5aW9Cg==“,那麼url則為 “login.php?name=5L2g5aW9Cg==”,PHP服務端對base64引數的解析程式碼如下:
PHP解析base64編碼引數Code Block-4:
if(preg_match("/==$/", $user_name)){
$user_name=base64_decode($user_name);
}
【轉載請註明出處:http://blog.csdn.net/leytton/article/details/51647663】