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

来源:互联网 发布:如何快速入门java 编辑:程序博客网 时间:2024/05/21 22:43

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())--nilwifi.setmode(wifi.STATION)wifi.sta.config("SSID","password")print(wifi.sta.getip())--192.168.18.110
参考 http://nodemcu.com/index_cn.html

2、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    endend)

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





2 0
原创粉丝点击