DEV Community

wei chang
wei chang

Posted on • Edited on

Harmonyos Cangjie Language Development Tutorial: Network Requests and Data Parsing

Now I can understand that Huawei constantly encourages everyone to contribute their own tutorials on the Internet. Without tutorials or references, the development process of the Cangjie shopping application was truly arduous. Every step was like crossing a river by feeling for the stones. However, it is hoped that through the article by You LAN Jun, everyone can avoid some detours.
Today, taking the classification list of shopping applications as an example, I will share how to make network requests in the Cangjie development language and how to display the requested data on the application.

Network permission

Network permission is a default rule in app development. In almost any system's app, network permission must be obtained before making a network request, and Cangjie is no exception.
In Cangjie language, requests for network permissions are still made in the module.json5 file. Add network request permissions under the module directory:

"requestPermissions": [{"name": "ohos.permission.INTERNET"},]

Network request

After adding permissions, you can return to the application to make requests. First, import the http module:

import ohos.net.http.*

Then create a request instance:

let httpRequest = createHttp()

Usually, we also need some configuration information, such as the request method and so on. In Cangjie, this parameter type is HttpRequestOptions, which contains many parameters. I will only introduce a few common ones

method: Request method
extraData: The content passed during the post method
expectDataType: Specifies the type of the returned data
header: Request Header
Here is a complete data request for everyone:

let url = "***/api/class.php"
let httpRequest = createHttp()
 let option = HttpRequestOptions(
    method: RequestMethod.GET,
    expectDataType: HttpDataType.STRING,
    header: HashMap<String, String>([("content-type", "application/json")])
)
httpRequest.request(url, {err, resp =>
    if (let Some(e) <- err) {
         CJTools.log('error:' + e.message)
    }
    if (let Some(r) <- resp) {
          CJTools.log(r.result.toString())
     }

     //请求完成务必销毁实例
     httpRequest.destroy()
    },options:option)
Enter fullscreen mode Exit fullscreen mode

Data parsing

Looking at the above code, it seems that you can understand everything from creating an instance, configuring parameters to initiating a request. However, when it comes to the request callback, You LAN Jun is a bit confused. For instance, I can't understand the code like let Some(e) < -err at all. I guess many of you are in the same situation as me.
Now let me introduce to you what "Some" means. It means to construct an instance carrying the parameter Option, indicating that it has a value. That is to say, the two if statements above are for judgment. The first one is to determine that if err has a value, it indicates that the request has gone wrong. If resp has a value, it indicates that the data has been requested.
That is to say, if the request is successful, the r in Some(r) is the data we have requested.
The current r should be of string type. So, how can we convert it into an array and make it traversable by components?
I first created a structure that is the same as the data content field:

public class ClassItem{
    private var id: String;
    private var classname: String;
    private var cover: String;

    public ClassItem(id:String, classname:String,cover:String){
        this.id = id
        this.classname = classname
        this.cover = cover
    }
     public func getId():String{
        return this.id
    }
    public func getClassname():String{
        return this.classname
    }
    public func getCover():String{
        return this.cover
    }
}
Enter fullscreen mode Exit fullscreen mode

Then I'll demonstrate for everyone how to convert r into an array composed of class items:

if (let Some(r) <- resp) {
        let str = r.result.toString()
        let jValue = JsonValue.fromStr(str)
        let jArray = jValue.asArray()
        for (i in 0..jArray.size()) {
            var model = DataModel.fromJson(jArray.get(i).getOrThrow().asObject())
            var modelData = match (model) {
            case data: DataModelStruct => data
                case _ => throw Exception("this data is not DataModelStruct")
             }
            let item = ClassItem(String.deserialize(modelData.get('id')), String.deserialize(modelData.get('classname')), String.deserialize(modelData.get('cover')))
            this.classList.append(item)
        }
    }
Enter fullscreen mode Exit fullscreen mode

Finally, the classList is the data we need. The above is all the relevant content about Cangjie language network requests.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.