NodeMCU教程 http.get请求及上传中文乱码解决方案

发布时间:2016-07-12 13:19:53 阅读:993次

转:http://blog.csdn.net/leytton/article/details/51647663

http://nodemcu-build.com/

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:

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. print(wifi.sta.getip())  
  2. --nil  
  3. wifi.setmode(wifi.STATION)  
  4. wifi.sta.config("SSID","password")  
  5. print(wifi.sta.getip())  
  6. --192.168.18.110  
参考 http://nodemcu.com/index_cn.html

2、PHP服务端

PHP服务端通过_GET['xxx']即可获取到GET请求参数。代码如下:

PHP服务端代码Code Block-2:

[php] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2. $user_name = isset($_GET['name'])?$_GET['name']:null;  
  3. $user_pwd = isset($_GET['pwd'])?$_GET['pwd']:null;  
  4. $message = array(  
  5.         "type" => 0,  
  6.         "data" => "name:".$user_name." pwd:".$user_pwd  
  7. );  
  8. echo json_encode($message);   
  9. ?>  

3、NodeMCU请求

代码如下,我们通过cjson模块来解析PHP服务端返回的Json数据并且遍历输出。

NodeMcu进行php.get请求代码Code Block-2:

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. http.get("http://192.168.1.106/login.php?name=aa&pwd=11", nil, function(code, data)  
  2.     if (code < 0) then  
  3.       print("HTTP request failed")  
  4.     else  
  5.       print(code,data)  
  6.       t = cjson.decode(data)  
  7.       for k,v in pairs(t) do print(k,v) end  
  8.     end  
  9. end)  

4、中文参数乱码解决

NodeMCU对GET请求的URL参数中文支持并不好,我们可以使用Base64编码后的参数。比如说"你好"的base64编码为 ”5L2g5aW9Cg==“,那么url则为 “login.php?name=5L2g5aW9Cg==”,PHP服务端对base64参数的解析代码如下:

PHP解析base64编码参数Code Block-4:

[php] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. if(preg_match("/==$/"$user_name)){  
  2.     $user_name=base64_decode($user_name);  

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询

转载请注明: NodeMCU教程 http.get请求及上传中文乱码解决方案 出自老鄢博客 | 欢迎分享