LuatOS Development: HTTP Example

LuatOS Development: HTTP ExampleRead the latest documentation and participate:[Document Error Reporting for Rewards] Activity

The latest document content can be found at:

https://docs.openluat.com/air724ug/luatos/app/socket/httpLuatOS Development: HTTP Example

1.Overview of HTTP

This section provides a brief introduction to HTTP. For more detailed explanations or protocol documents, please refer to relevant websites or documents.

1.1 HTTP Request Methods

The HTTP/1.1 protocol defines eight methods for manipulating specified resources in different ways.

a. GET

Requests a specified resource. The GET method should only be used for reading data.

b. HEAD

Similar to the GET method, it requests a specified resource from the server, but the server does not return the body of the resource.

c. POST

Submits data to the specified resource, requesting the server to process it, such as uploading a file.

d. PUT

Uploads the latest content to the specified resource location.

e. DELETE

Requests the server to delete the resource identified by the Request-URI.

f. TRACE

Echoes back the request received by the server, mainly used for testing or diagnostics.

g. OPTIONS

This method allows the server to return all HTTP request methods supported by the resource. Using ‘*’ to replace the resource name, sending an OPTIONS request to the web server can test whether the server functions properly.

h. CONNECT

Reserved in the HTTP/1.1 protocol for proxy servers that can change the connection to a pipeline mode. Typically used for SSL encrypted server connections.

HTTP servers should implement at least the GET and HEAD methods; other methods are optional.

1.2 HTTP Status Codes

The first digit of the status code represents the type of response:

1xx Informational – The request has been received by the server and is continuing to process.

2xx Success – The request has been successfully received, understood, and accepted by the server.

3xx Redirection – Further action is needed to complete the request.

4xx Client Error – The request contains a syntax error or cannot be fulfilled.

5xx Server Error – The server encountered an error while processing a valid request.

RFC 2616 recommends descriptive phrases for status, such as “200 OK” and “404 Not Found”.

1.3 URL Structure

The address of the Hypertext Transfer Protocol (HTTP) consists of five basic elements:

a. Transfer protocol, hierarchical URL marker (fixed as [//]), credential information required to access the resource, usually a domain name, but can also use an IP address.

b. Port number, represented numerically, with HTTP defaulting to “:80”, which can be omitted.

c. Path, with the character “/” distinguishing each directory name in the path.

d. Query, form parameters in GET mode, starting with the “?” character, with each parameter separated by “&” and the parameter name separated from the data by “=”.

e. Fragment, starting with the “#” character.

Since the Hypertext Transfer Protocol allows the server to redirect the browser to another web address, many servers allow users to omit parts of the web address, such as “www”.

This article demonstrates the specific implementation of HTTP and HTTPS protocols through several concrete examples.

2. Overview of Function Demonstration

2.1 Demonstration Content

This article demonstrates common operations and uses of HTTP based on the author’s own experiences and practices, including:

a. Implementation of the GET method;

b. Implementation of the POST method;

c. File upload operations;

d. File download operations;

e. HTTPS encrypted communication;

f. Handling JSON data;

g. Gzip operations.

3. Hardware Environment Preparation

3.1 Development Board Preparation

All demonstrations mentioned in this article are completed using the EVB_Air724UG_A14 development board.

For detailed usage instructions of this core board, refer to:https://docs.openluat.com/air724ug/product/

For detailed usage instructions of this development board, refer to the “EVB_Air724UG_AXX Development Board User Manual”; the latest version of the user manual at the time of writing this article is: “EVB_Air724UG_A14 Development Board User Manual”; if you encounter any issues during the use of the development board, you can refer directly to this user manual.

In mainland China, a SIM card that can access the internet is generally acceptable, such as IoT cards or mobile phone cards from China Mobile, China Telecom, or China Unicom.

3.2 Wiring Method of the Development Board

LuatOS Development: HTTP Example

First, place the development board properly, connect it to the computer via USB, and remember to connect the antenna to ensure a good signal environment, for example, you can check the mobile phone signal to assess the signal status of the environment. The USB connection is shown in the above image.

In the above image, there is a USB label next to the USB port; when downloading scripts, you must connect to this port. The other USB port is the USB to UART interface, which can be used to view debug TRACE information through serial port tools. In the testing environment of this article, USB printing trace is used, that is, in the Luatools tool, select “usb print trace” without needing to connect the serial port to monitor the printed trace information.

3.3 Firmware Operation Related Content

a. Luatools is an essential tool for downloading firmware and scripts, and it is also very convenient for viewing TRACE debug information.

https://docs.openluat.com/Luatools/

b. For the usage of Luatools, please refer to:

https://docs.openluat.com/blog/Luatools/

c. For remote firmware upgrades, please refer to:

https://docs.openluat.com/blog/fota_lesson/

d. For USB driver installation, please refer to:

https://docs.openluat.com/blog/usb_drv/

4. Software Environment Preparation

4.1 Lua Script Language

This article is based on the Lua script language, so a basic understanding of Lua script language is required. You can learn more through the following documents:

For the syntax of the Lua script language, please refer to:

https://wiki.luatos.com/luaGuide/luaReference.html#lua-5-3

https://docs.openluat.com/blog/lua_lesson/

4.2 HTTP API of Lua Script Language

Since this article discusses HTTP, in addition to the brief explanation in the HTTP overview, it is also necessary to understand the API of the Lua script language. The HTTP API interface definition is as follows. The reason I am posting the following definition code is threefold.

a. First, of course, the comments in the explanation provide a clear definition of the HTTP protocol structure;

b. Secondly, the explanation of parameters is more comprehensive than the demonstration document testHttp.lua file content, which is more beneficial for readers to understand the various parameter forms. For example, the expression for passing certificates is clearer, making it easier for everyone to organize parameters with a clear understanding;

c. Finally, many calling examples are provided, and these examples are not included or are not comprehensive in the testHttp.lua document, while the examples here can serve as a good supplement.

For specific explanations of the HTTP interface, readers can also refer to other related materials or reference other documents.

4.3 Auxiliary Tools

To effectively analyze problems that may arise during development and to view data, it is necessary to prepare some auxiliary tools, which will greatly shorten the time for everyone to solve problems. Several tools used during the writing of this article are introduced, and these tools will be mentioned or used later in the article, so please familiarize yourself with them in advance.

a. Progress Telerik Fiddler Classic, a packet capture tool.

https://downloads.getfiddler.com/fiddler-classic/FiddlerSetup.5.0.20244.10953-latest.exe

b. Postman, an API debugging platform tool that can conveniently validate various operations mentioned in this article.

https://dl.pstmn.io/download/latest/win64

c. httpbin.org, a very good API debugging website, many of the demonstrations related to HTTP in this article are completed using this website.

5. Basic Usage of Luatools

5.1 Preparing Demonstration Code

This article uses the demonstration code testHttp of the air724 module as a template, revising and modifying it to complete the content mentioned in Chapter 2 of this article. This demonstration template consists of two files: main.lua and testHttp.lua. If you are familiar with it, you can skip this; if you are not familiar and do not want to go through the trouble of downloading resources, you can directly copy and use it. The testHttp.lua will be revised during the testing process of this article, and the complete file containing all revisions will be provided at the end of this article.

5.2 Using Luatools

After connecting the development board as described in Section 3.2 of this article, and confirming that everything is correct, we can start the Luatools tool, as shown in the following image. Click the “Project Management and Testing” button, and a window will appear as shown in the image below. Click “Create Project” and enter the project name, such as the project name established in this article, http_doc.

After the project is created, click to add scripts or resource files, and as mentioned in the previous section, add the template main.lua and testHttp.lua, as shown in the image.

Enable “usb print trace” and select “Add Default lib”.

LuatOS Development: HTTP Example

After completing the above operations, you also need to select the underlying CORE. Since the Hezhou module has various resources, the content supported by different underlying CORES varies. These underlying cores are generally installed in the resource subdirectory of the tool’s directory. Open this directory, and there will be different options, as shown in the image. Since the 724ug module belongs to the 8910 platform, we need to select one of the 8910 cores. This article refers to developing in the Lua script language, so we choose 8910_lua_lod. Click to enter, and there are multiple cores; we select the most basic LuatOS-Air_V4028_RDA8910.pac. If the core you are using has been upgraded, there may be some differences, such as version number changes, so please pay attention to that.

LuatOS Development: HTTP Example

If the firmware mentioned above is not available on your computer, you can download it from the following URL.

Firmware version and upper layer scripts: https://docs.openluat.com/air724ug/luatos/firmware/

6. GET Request Demonstration

6.1 Demonstration Website httpbin.org

To make the demonstration in this article directly usable and to obtain results, rather than just providing a sample text, it is necessary to find a website that can be tested. This article uses the API provided by httpbin.org mentioned in the tools preparation above for testing.

First, open the httpbin.org website and find the Dynamic data section, then click the dropdown menu, as shown in the image.

LuatOS Development: HTTP Example

Find the Dynamic data section and open it, as shown in the image below.

LuatOS Development: HTTP Example

In the above, the first item is the GET method, and the URL is /base64/{value}, indicating that using the GET method can obtain the base64 encoded content from this connection (URL), which means restoring the value to the actual content, i.e., decoding it. Let’s complete this task.

6.2 Implementing Base64 Decoding API with GET Method

We can use the crypto.base64_encode function to perform base64 encoding on the character. In testHttp.lua, find the line http.request(“GET”, “www.lua.org”, nil, nil, nil, nil, cbFnc) and define a local variable before the statement and assign the value “Using Hezhou 724ug module to complete HTTP GET method”, i.e., local base64_str = “Using Hezhou 724ug module to complete HTTP GET method”.

According to the API description, replace the URL path “www.lua.org” with “httpbin.org/base64/”..crypto.base64_encode(base64_str, base64_str:len()).

After the revision, it looks like this. Save the file and use Luatools to download the script to the development board to see the result.

Special Note

If this is the first download, you need to select the download of the underlying core and the script because you do not know what core is in the development board you received. If the core is incorrect, it will not run, so please remember this. After completing the underlying download, if the script is revised again, you only need to download the script.

After the download is complete, it will automatically start and display trace information in the Luatools tool. Let’s look at the result, as shown in the image.

LuatOS Development: HTTP Example

In the above image, you can see the result true 200, indicating successful completion, and the HTTP status code is 200.

At the same time, the decoded string “Using Hezhou 724ug module to complete HTTP GET method” is returned.

Thus, the demonstration of GET is successfully completed.

6.3 Complete Code Convention

For convenience, this article will list the complete testHttp.lua code at the end. All revisions made in this article will be retained in the testHttp.lua file, using comment symbols like “–[[” and “]].” to select whether to use or not.

7. POST Request Demonstration

7.1 IoT Card Information API Interface

The GET demonstration feels quite easy, and there were no obstacles along the way. However, the GET we used is not in a real application scenario, as the server is still just a demonstration. In the POST, we will use real application data, which counts as a real project application.

To demonstrate, we need a server that allows us to operate. As mentioned above, we need to complete a real project. Using the 724ug module requires an internet card, and an IoT card is the best choice. Here is an API interface provided by an IoT card service provider for IoT SIM card information, and this website is

http://sim.taoyuan-tech.com. This is a real website, and it provides a test account for customers, so we will use this test account to perform POST method operations to read the SIM card logs.

The username for the test account is: 18168967871, and the password is: 18168967871. After logging in, it looks like the image below.

LuatOS Development: HTTP Example

In the interface shown in the image, click the button labeled “Get API key and Secret” to obtain the test user’s API key and API Secret, and be sure to save these two pieces of data for later use. Click the button labeled “API Documentation” to enter the detailed API interface documentation page, as shown in the image.

LuatOS Development: HTTP Example

Looking at the documentation directory, the items to pay attention to are listed in the first few items, which are short enough to be fully visible in one image, as shown in the image below.

LuatOS Development: HTTP Example

In the image above, we see several important notes.

a. All request parameters must be sent in JSON format. This means that only JSON format data and content will be accepted;

b. A status code of 200 is required for a correct response;

c. The units used are specified, making it easy to calculate time and costs;

d. Authentication is explained, which is very important, so read and understand it carefully. The authentication method is HTTP Basic Authorization, and the authentication information is in the form of appkey:appsecret, which are the two pieces of data mentioned earlier that need to be saved;

e. Possible error codes are explained;

f. The host address is given as http://api.taoyuan-tech.com/api/open.

All these agreements and notes are very important, do not overlook them, as we may need to use them later.

This API has several interfaces, and we will just implement the first one, which is the log query shown in the image below. The fields provided in the table are the access parameters and return results we need to provide.

LuatOS Development: HTTP Example

7.2 Using Postman Tool for Validation

For convenience, we can first use Postman to organize the package content, and then transplant it into the testHttp.lua file for testing. Looking at the API documentation for the “IoT Card Usage Log Query” API, we know that the access URL for this interface is “/iotcard/usagelog”, so the complete access path is http://api.taoyuan-tech.com/api/open/iotcard/usagelog. Fill this path into Postman, select the POST method, and set the header information Auth Type to Basic Auth. These contents are all determined by the API documentation agreements and notes. Then click Auth and fill in the Apikey and Apisecret mentioned earlier into the username and password input boxes, respectively, as shown in the image.

LuatOS Development: HTTP Example

Next, click Body and enter the following content:

The meanings of the fields are explained in the table shown in the previous image, so please pay attention to check. The 89860403102080512138 is the ICCID number of the SIM card, which can be found in the card information of the test user account. If this number is not found in the card information, you can check the card information to obtain the actual ICCID number that exists in the user database. From the explanation in the image, we also know that the passed parameters can be one of the other three identification numbers, such as the IMEI number. Among the four SIM card identification numbers, we choose ICCID; if you want to test other parameter forms, you can modify it accordingly. For example, if modified to IMSI, the input content would change to:

As shown in the image.

LuatOS Development: HTTP Example

After completing the input, click Send to send the request. The response will be as shown in the image below.

LuatOS Development: HTTP Example

According to the table content shown in the previous image, the data usage for the day 2024-10-10 is 0M, i.e., “data_usage”:0. At the same time, the status code is 200, and the result is OK. After completing these, we can revise the testHttp.lua based on the packaged information.

7.3 Revising File Content

Open the testHttp.lua file, and between lines 77 and 84, we find a segment of code that uses the POST method, which can be revised as follows. First, remove the comments, and then check the specific content. We find several points of doubt.

LuatOS Development: HTTP Example

a. From the above, it is known that the API uses the Auth Basic method, and in the above packaging, the Apikey and Apisecret were used, which seems to correspond to the code’s [“Authorization”]=”Basic jffdsfdsfdsfdsfjakljfdoiuweonlkdsjdsjapodaskdsf”, but it also seems not to match. How do we obtain this string?

b. It was mentioned earlier that the Content-type used is application/json, which differs from the method used in the code, so this needs to be revised;

c. At the same time, the content of the request parameters also needs to be revised, but how to organize these parameters? From the various organization methods of the table type, there is no name:value format.

Having questions is good; we can solve them one by one. First, we will use the packet capture tool provided at the beginning of this article to see what the actual data looks like, and we will know it. Directly showing the image, as shown in the image below, we can see what the actual data packets contain. Of course, this packet capture tool can also view the BODY, auth, and other data, and you can switch between pages to see what data items are available to deepen your understanding.

LuatOS Development: HTTP ExampleLuatOS Development: HTTP Example

In the image above, we see a line of text: Authorization: Basic NkZhbXFsRmZTVmQ4OHNHejpLemt0SW8y …… this is exactly what we need, so we will copy this item and replace it.

The second question is simple; just revise it to [‘Content-Type’]=”application/json”.

The third question requires calling a JSON function to solve it, which is the function below, i.e., JSON encoding.

As for whether to add [‘Connection’]=”keep-alive”, some examples in the code add it while others do not. HTTP is a short connection, but it is hoped that the environment can be preserved so that the next HTTP request can be responded to quickly, which is why the [‘Connection’]=”keep-alive” configuration item exists. However, in HTTP 1.1 and later, this is the default value, so it can be added or not, and the effect is the same.

After the above revisions, the code becomes as follows.

Now, we will download the script to the development board and see what the result is.

LuatOS Development: HTTP Example

If all goes well, as shown in the image above, you can see that the returned status code is 200, and the result is true, indicating that the code executed correctly. At the same time, you can see that the data returned by the server is consistent with the data obtained from Postman.

At this point, the demonstration of POST is considered complete. Additionally, it should be noted that the Auth Basic structure in the header can also be obtained by directly calling the base64 function in the crypto module. The code is shown below.

How to use it specifically depends on the actual situation, as some APIs provided by websites directly provide BASE64 codes, in which case the first method is obviously more convenient. The complete source code used in this article will be provided at the end.

8. File Upload Operations

8.1 Preparation Work

For file uploads, we will still use the testing server used in the GET method, i.e., httpbin.org, because we are using the “post” method to upload files, so the URL is httpbin.org/post. It should be noted that httpbin.org/post is a loopback server, meaning that when files are transmitted to it, the server will return the transmitted content as a response. Therefore, when we see the response and returned content, we can determine whether the operation is correct. In fact, I considered using a more direct method, but after several days of searching, I couldn’t find a suitable server to operate on, so I had to use this as the file upload demonstration in this article.

As before, we will first use the Postman tool to organize the data packet.

a. Start Postman and select the POST method;

b. Enter “httpbin.org/post” in the host field;

c. Then select body and choose binary;

d. Select the file, which is test.txt, with the content “uses post method to upload a file.” If you do not have this file, you can create one;

e. Click send;

f. Wait for the returned data.

All operations and data are shown in the image below.

LuatOS Development: HTTP Example

In the image, you can clearly see the 200 OK text, indicating that the operation is correct. At the same time, in the text pointed out by the arrow number 6 in the image, we can find some useful strings, which are:

At the same time, we also found:

“files”:{}

“form”:{}

is empty, which we can compare with the content of multiple file uploads with multiple parameters later to understand.

8.2 File Revision

As in the previous method, we will revise the content of the testHttp.lua file.

In the testHttp.lua file, starting from line 56, there is a piece of commented-out code that we can use. As shown in the image.

LuatOS Development: HTTP Example

First, remove the comment brackets, replace the URL with “httpbin.org/post”;

Secondly, replace the value of [‘Content-Type’] with the content mentioned earlier, i.e., “text/plain”;

Finally, change {[1]={[‘file’]=”/RecDir/rec001″}} to {[1]={[‘file’]=”/luar/test.txt”}} and save.

The revised text is listed as follows.

8.3 Firmware Download and Running Results

Start the Luatools firmware download tool, and click the project management test button to add the files main.lua, testHttp.lua, and also add the file test.txt, as shown in the image. It should be noted that the project location you create may differ, and the file paths in the image may differ from your actual content, so just ensure they match your actual content.

LuatOS Development: HTTP Example

In the image, click to download the script, then switch to the trace page of Luatools and wait for the script code to run results.

LuatOS Development: HTTP Example

From the content in the image, the script reproduces the content demonstrated in Postman, and the content we focused on in the previous text is also confirmed in the image, as seen in the content within the red box, which can be compared with the content of Postman.

At this point, the file upload can be successfully completed. Some may ask, the file has been uploaded, but what if I need to upload a binary file, or how to handle uploading an image? In fact, it is also very simple; we will still use Postman to conduct package testing, as shown in the image.

LuatOS Development: HTTP Example

In the image, we remove test.txt and replace it with test.bin, and change the content type of the script to “application/octet-stream”; everything else remains unchanged, where application/octet-stream indicates that the data content is a binary stream. After clicking SEND, you can see the returned information. After downloading the revised content using Luatools, wait for the running results as shown in the image. The relevant results are also consistent with Postman. Of course, here are a few special points to note.

a. Please pay attention to the file size; too large files may lead to insufficient memory, so larger files need to be processed in other ways.

b. Please also add related resource files to the project and download them to the module along with the script.

c. For binary files, the content is base64 encoded, so after the file is uploaded, it needs to be decoded when actually used.

LuatOS Development: HTTP Example

8.4 Advanced File Upload

Some applications may require uploading files while also passing parameters; how should this be handled? We look at the testHttp.lua file, where there is a segment of code starting from around line 90. We can use this segment of code to perform more complex file upload operations, such as uploading multiple files and multiple parameters. The following code is the corresponding code segment in the testHttp.lua file after removing comments.

In the above code, two parameters are passed, namely the IMEI card number and time, and one file, “logo_color.jpg”. We need to revise it for our use. First, we will change the URL to “httpbin.org/post”, and at the same time, we will change the uploaded file to “/lua/text.txt”. In addition, we also need to revise one file type, namely txt = “text/plain”, indicating that this is a text file. If it is a BIN file, we need to add a BIN=”application/octet-stream”, and so on.

After revising the above, the testHttp.lua becomes as follows. This is the complete code for the advanced section, and you can directly copy it for use. To save space in this article, this code is an example of transmitting two files and two parameters, and I will not explain other combinations such as one file and one parameter.

After revising the above code, add it along with main.lua, text.txt, and text.bin to the project files, as shown in the image. If you do not have a text file, you can create one, and for binary files, you can find a smaller one on your computer, such as I found a binary firmware test.bin for a microcontroller. The files should not be too large to avoid memory issues, which is also a practical consideration, meaning that file handling should be treated with caution in real applications.

LuatOS Development: HTTP Example

After the download is complete, we check the running results, as shown in the image.

LuatOS Development: HTTP Example

In the image above, we found true 200 indicating a correct return, and then we found the relevant data of the first file test.bin. Due to window size limitations, the content of the second file is not displayed, but we can scroll to see the content of the second file, as shown in the image.

LuatOS Development: HTTP Example

In the image, we found the information of the second file, and the text file was not base64 encoded. At the same time, the content of the two parameters can also be found.

Next, let’s talk about how to define file types, as we see that the definitions of file types are a bit confusing. In the code below, there are jpg=”image/jpeg” and png=”image/png”, while the two file types we added are not clear on why they should be filled this way.

This still needs to refer back to the two tools, Postman and Fiddler. When we organize demonstrations in Postman, after sending, we can see the specific data format in Fiddler. In Fiddler, switch to WebForms, as shown in the image.

LuatOS Development: HTTP Example

In the image, the data of each file is converted into two tables, and the values of Content-Type, as shown in the image, are application/octet-stream and image/png, respectively, which should be filled into the corresponding file types. Following this method should generally not go wrong.

9. File Download

Downloading files via HTTP is relatively simple in principle, but due to the difficulty in finding servers and the large size of files on regular websites, it took a lot of time. Fortunately, I finally found a website that I consider quite useful for testing file downloads: Douzi External Link: http://zuoye.free.fr/index.php. Currently, the website is available and can be used for file download testing. Entering the website will bring up an upload file interface, allowing you to upload your own file and then use HTTP to download this file for verification. Of course, you can also use files that have already been uploaded in the file square.

LuatOS Development: HTTP Example

We will copy the external link address of the file, then revise the testHttp.lua file. Comment out all other test demonstration statements, then add a line of code in the testHttp.lua file, save it, and download it to the development board.

Below are the running results.

LuatOS Development: HTTP Example

We can see the true 200 text, indicating that the website returned correctly. Then we see that the file name is flag.png and the file size is 785, and the file type is an image. The file content is also displayed, but since it is an image file, it cannot be displayed here. However, we can check the properties of the file I just uploaded to compare whether the file size matches, as shown in the image. Of course, binary data cannot be displayed, but we can modify the callback function and use base64 encoding to display the data, but this content is not within the scope of this demonstration, and interested friends can try it themselves.

LuatOS Development: HTTP Example

10. HTTPS Encrypted Communication

For encrypted communication, we will use the server “https://airtest.openluat.com” for testing. Using the GET method to access this server will return the word hello. Open the link https://doc.openluat.com/share_article/KwExQpfcbL9Fs, which is the server’s usage instructions and entry for various functional interfaces, as shown in the image.

LuatOS Development: HTTP Example

Click on the HTTPS Server to enter the relevant instructions, as shown in the image.

LuatOS Development: HTTP Example

You can see the server’s instructions and startup methods, and at the end, there is a cert.rar compressed file. Click to download it, which contains three certificate files. Unzip and save these three files, and add them to the Luatools project files, as shown in the image.

LuatOS Development: HTTP Example

After completing the above operations, the next step is to revise the testHttp.lua file, adding the content below and saving it. Then go to the Luatools tool and click to download the script.

After a few seconds, the development board will restart and run, and the results are as follows.

LuatOS Development: HTTP Example

11. Handling JSON Data

JSON data processing mainly involves two functions, namely json.encode and json.decode. In fact, we have already used the json.encode function in the POST section, so we will not explain the encode function in this section. In this section, we will directly read JSON data from the website and then call json.decode to decode it.

This time we will still use the httpbin.org website to do this. This website has an interface that can be used to test this function, located in the Dynamic data section under the GET method, with a GET/stream/{n} interface that returns n groups of JSON data based on the value of {n}. The following image shows the case when n=4.

LuatOS Development: HTTP Example

We will copy the body part out and list it as follows:

The above string cannot be parsed directly using json.decode() because it contains multiple JSON strings, so it needs to be separated. Therefore, we wrote the following code to separate the strings. From the above code, the end of line 1 and the beginning of line 2 contain the string “}{“, and as a JSON text, this string only exists between two JSON strings, so we use this as a substring search to accurately find each JSON substring. At the same time, we will rewrite the callback function to distinguish it from the original callback function, naming this callback function cbFncJson. Additionally, to clarify the program, we also wrote a JSON string parsing output function json_out. The code is listed below. Note: The following string processing function is only suitable for the specific data demonstrated in this article; if used in other situations, please revise or supplement it according to the format and content.

After completing the above code, add a line of code in testHttp.lua to use the GET method to retrieve the data.

Save the file and download it to the development board. Let’s see the execution results. For convenience, we will copy the parsing string and list it as follows, removing some unnecessary outputs and retaining the JSON parsing part for clarity.

The output method of the above text first outputs the JSON string, followed by the parsing of the JSON string, listing each name pair in a certain order.

Although the above code is for displaying JSON, it actually comprehensively uses various data types such as table, JSON, and string, making this a relatively comprehensive demonstration. Everyone can use this as a basis for further testing demonstrations to complete more complex content.

12. Gzip Operations

This operation uses the code below for testing. Since 724 does not yet have a suitable decompression tool, no explanation will be provided; only the test content and results will be listed.

LuatOS Development: HTTP Example

LuatOS Development: HTTP Example

13. Final Test File

The final testHttp.lua file contains all the demonstration content of this article. When using it, remove the corresponding comments; when not using that function, restore the comments.

LuatOS Development: HTTP Example

14. Summary

This article strives to demonstrate most methods of the HTTP protocol based on practical applications, and each operation has been personally tested. The selection of some servers mentioned in this article was also made after extensive searching and comparison, ensuring a certain level of stability, meaning that the corresponding resources are available within a certain time frame. Finally, I hope this article is useful to readers and can solve some practical problems.

15. Frequently Asked Questions

15.1 No response after downloading the script.

Check if the underlying core has been downloaded, as the development board is generally in AT version when it leaves the factory. If the underlying core is not downloaded, the Lua script will not run.

15.2 Cannot download after connecting the USB cable, and the light does not flash.

Check if the USB cable is connected correctly. The 724 development board has two USB ports, and the one labeled USB is the one used for downloading. The other USB port is the USB to TTL UART communication port, which does not provide power support, so it will not respond.

15.3 What to do if it accidentally bricks?

In the Luatools software, click to download firmware, select the underlying core file, enable USB BOOT download, hold down the reset button on the development board until you hear a beep, then start downloading. When you see the prompt to release the button, you can let go. As shown in the image.

LuatOS Development: HTTP Example

15.4 Always unable to connect to the internet.

Check if the antenna is connected properly, check if the signal in the location is good, check if the SIM card is locked, check if the SIM card is out of balance, etc. You can use your own mobile phone card to swap in for comparison. If the mobile phone card can access the internet, then it is not related to the hardware; at this point, you can check the relevant content of the SIM.

LuatOS Development: HTTP Example

â–¼ Contact Hezhou Marketing Department â–¼

LuatOS Development: HTTP Example

Scan the QR code to add friends on WeChat/Enterprise WeChat

â–¼ Learn more about Hezhou â–¼

4G+Location+WiFi+Bluetooth, Air8000 Industrial EngineNew Hezhou Air8101 Development Board Now Available

Low Power Open Development New Solution Air780EPM

LuatOS Development: HTTP Example

Leave a Comment