AliOS Things 3.0应用笔记:http client简单应用

简介: AliOS Things 3.0版本新增加了httpc组件(http 客户端组件),httpc组件支持多种RESTful的API调用,包括GET、POST、PUT、HEAD等,也支持https安全协议。


给AliOS Things一颗STAR(前往GitHub关注我们)

目录

          简介

          准备工作

          创建应用工程

          编写应用代码

                添加http组件

                天气API说明

                使用http组件

                完整源码

            编译运行

           参考文档

简介

AliOS Things 3.0版本于9月27日在云栖大会正式发布,在新版本中带来了全新的应用开发框架,帮助用户快速构建自己的应用。使用户可以更专注于自身应用的开发。

AliOS Things 3.0版本新增加了httpc组件(http 客户端组件),httpc组件支持多种RESTful的API调用,包括GET、POST、PUT、HEAD等,也支持https安全协议。

准备工作

参考AliOS Things Environment Setup 和AliOS Things 3.0 应用开发指南 搭建好AliOS Things 3.0的应用开发环境。

创建应用工程

参考AliOS Things 3.0 应用开发指南 > AliOS Studio中创建应用工程创建好你的应用工程。

本示例新建的应用工程名称为httpclient_app,选择的开发板为developerkit。

编写应用代码

新建好的应用工程文件如下面所示:

.httpclient_app├──.aos# AliOS Things 3.0 应用工程描述├──.vscode# AliOS Studio 配置文件├── Config.in# Menuconfig 配置文件├── README.md# 应用说明文档├── aos.mk# 编译文件├── app_main.c# 应用示例代码└── k_app_config.h# 内核配置

添加http组件

aos-cube会自动根据include的头文件来自动添加组件。

http组件需要用到全局宏:BUILD_AOS,所以需要在aos.mk中额外增加一个全局宏定义:

GLOBAL_DEFINES += BUILD_AOS

天气API说明

本示例使用http组件,发送http get请求获取天气数据,天气的API是中国天气网提供的API:http://www.weather.com.cn/data/sk/101210101.html,其中101210101代表是杭州。

使用curl命令可以测试该API接口:

$ curl http://www.weather.com.cn/data/sk/101210101.html{"weatherinfo":{"city":"杭州","cityid":"101210101","temp":"24.8","WD":"东北风","WS":"小于3级","SD":"81%","AP":"1000.3hPa","njd":"暂无实况","WSE":"<3","time":"17:50","sm":"2.1","isRadar":"1","Radar":"JC_RADAR_AZ9571_JB"}}%

或者也可以在浏览器打开该链接测试API接口。

使用http组件

本示例主要使用到了http如下接口,详细的http对外提供的接口和参数说明请参考include/network/http/http.h

/* httpc 初始化 */int8_thttp_client_initialize(void);/* 创建一个httpc实例 */httpc_handle_thttpc_init(httpc_connection_t*settings);/* 销毁一个httpc实例 */int8_thttpc_deinit(httpc_handle_thttpc);/* 发送http请求 */int8_thttpc_send_request(httpc_handle_thttpc,int8_tmethod,char*uri,constchar*hdr,constchar*content_type,constchar*param,uint16_tparam_len);/* 构建http请求header */int32_thttpc_construct_header(char*buf,uint16_tbuf_size,constchar*name,constchar*data);/* 等待接口http返回 */int32_thttpc_recv_response(httpc_handle_thttpc,uint8_t*rsp,uint32_trsp_size,http_rsp_info_t*info,uint32_ttimeout);

完整源码

本示例应用的工程源码点击这里下载。

注意:需要更改app_main.c中的WIFI_SSID 和 WIFI_PASSWD 为你的路由器信息。

aos.mk:

NAME := httpclient_app$(NAME)_MBINS_TYPE := app$(NAME)_VERSION := 1.0.0$(NAME)_SUMMARY := httpclient_app$(NAME)_SOURCES += app_main.cGLOBAL_DEFINES += BUILD_AOSGLOBAL_INCLUDES += ./$(NAME)_COMPONENTS_CUSTOMIZED := http yloop$(NAME)_COMPONENTS += $($(NAME)_COMPONENTS_CUSTOMIZED)

app_main.c:

/*

* Copyright (C) 2015-2017 Alibaba Group Holding Limited

*/#include<stdio.h>#include<aos/kernel.h>#include<aos/yloop.h>#include<http.h>#include<network/network.h>#defineWIFI_SSID"aiot"#defineWIFI_PASSWD"12345678"#defineREQ_BUF_SIZE 2048#defineRSP_BUF_SIZE 4096#defineHTTP_UP_HDR_SIZE 128/* weather api hostname */#defineWEATHER_HOSTNAME"http://www.weather.com.cn/"/* weather api uri */#defineWEATHER_URI"data/sk/101210101.html"statichttpc_handle_thttpc_handle =0;statichttpc_connection_tsettings;/* buffer for send & receive */staticuint8_trsp_buf[RSP_BUF_SIZE] = {0};staticuint8_treq_buf[REQ_BUF_SIZE] = {0};/* send http get request */char*get_weather(void){intfd;charhdr[HTTP_UP_HDR_SIZE] = {0};int32_tret;http_rsp_info_trsp_info;    http_client_initialize();/* create socket */if((fd = socket(AF_INET, SOCK_STREAM,0)) <0) {printf("alloc socket fd fail\n");gotoexit;    }memset(&settings,0,sizeof(settings));    settings.socket      = fd;    settings.server_name  = WEATHER_HOSTNAME;    settings.req_buf      = req_buf;    settings.req_buf_size = REQ_BUF_SIZE;/* httpc initialization */if((httpc_handle = httpc_init(&settings)) ==0) {printf("http session init fail\n");        close(fd);gotoexit;    }/* construct httc header: set accept content type */if((httpc_construct_header(            hdr, HTTP_UP_HDR_SIZE,"Accept","text/xml,text/javascript,text/html,application/json")) <0) {printf("http construct header fail\n");gotoexit;    }/* send get request */if((httpc_send_request(httpc_handle, HTTP_GET, WEATHER_URI, hdr,"application/json",NULL,0)) != HTTP_SUCCESS) {printf("httpc_send_request fail\n");gotoexit;    }/* get response */if((httpc_recv_response(httpc_handle, rsp_buf, RSP_BUF_SIZE, &rsp_info,10000)) <0) {printf("httpc_recv_response fail\n");gotoexit;    }printf("http session %x, buf size %d bytes, recv %d bytes data", httpc_handle,        RSP_BUF_SIZE, rsp_info.rsp_len);// if (rsp_info.rsp_len > 0) {//    printf("%s", rsp_buf);// }if(rsp_info.message_complete) {// printf("message_complete");close(settings.socket);        httpc_deinit(httpc_handle);returnrsp_info.body_start;    }exit:    close(settings.socket);    httpc_deinit(httpc_handle);returnNULL;}/* task for get weather */staticvoidget_weather_task(void*arg){char*weather_data =NULL;/* get weather data */if((weather_data = get_weather()) !=NULL){        aos_msleep(200);printf("********************** weather data **********************\r\n");printf("%s\r\n", weather_data);printf("**********************************************************\r\n");return;    }printf("weather request error\r\n");}/* wifi event */staticvoidwifi_service_event(input_event_t*event,void*priv_data){staticcharip[16] = {0};staticintget_weather_started =0;if(event->type != EV_WIFI && event->code != CODE_WIFI_ON_GOT_IP) {return;    }    netmgr_wifi_get_ip(ip);/* start up only once */if(get_weather_started ==1) {return;    }/* check if ip is available */if(0==strcmp(ip,"0.0.0.0")) {printf("ip invailable\n");return;    }    get_weather_started =1;printf("wifi connected, ip:%s\n", ip);    aos_task_new("get_weather", get_weather_task,NULL,1024*4);}/* task for connect wifi */staticvoidwifi_connect(void*arg){/* network init */netmgr_init();    netmgr_start(false);    aos_msleep(100);/* connect to wifi */printf("\r\nConnecting to wifi: ssid:[%s], passwd:[%s]\r\n", WIFI_SSID, WIFI_PASSWD);    netmgr_connect(WIFI_SSID, WIFI_PASSWD,10*1000);}/**********************user code*************************/intapplication_start(intargc,char*argv[]){#ifdefWITH_SALsal_add_dev(NULL,NULL);    sal_init();#endif/* register wifi event */aos_register_event_filter(EV_WIFI, wifi_service_event,NULL);    aos_task_new("wifi_connect", wifi_connect,NULL,2048);/* loop for schedule */aos_loop_run();}

编译运行

点击编译和烧录。运行后,在串口日志最后面就能看的获取到的天气信息。

运行效果:

[  0.050]AOS sensor:  drv_acc_st_lsm6dsl_init successfully[  0.060]AOS sensor:  drv_gyro_st_lsm6dsl_init gyro do not need reset[  0.070]AOS sensor:  drv_gyro_st_lsm6dsl_init successfully[  0.080]AOS sensor:  drv_als_liteon_ltr553_init successfully[  0.090]AOS sensor:  drv_ps_liteon_ltr553_init successfully[  0.100]AOS sensor:  drv_baro_bosch_bmp280_init successfully[  0.110]AOS sensor:  drv_mag_memsic_mmc3680kj_init successfully[  0.120]AOS sensor:  drv_humi_sensirion_shtc1_init successfully[  0.130]AOS sensor:  drv_temp_sensirion_shtc1_init successfully            Welcome to AliOS Things[  0.150]sal_wifi Uart dev is not configured, use the default cfguart 1 enter uart_receive_start_dma instance 0x40004800ip invailableConnecting to wifi: ssid:[aiot], passwd:[12345678]wifi connected, ip:192.168.43.111[[hhttttppcc]][[000088665500]]  hhttttppcc__sseenndd__rreeqquueesstt,,  sseenndd  rreeqquueesstt  hheeaaddeerrvGoErTk s/pdaactea//gsikt/h1u0b1/2A1l0i1O0S1-.Thhtimnlg sH/TbToPa/r1d./1d2Ulsoepre-rAkgietn/ta:o sA/lbioOaSr-dH_TcTlPi-.Ccl i2e1n6t1Cache-Control: no-cacheConnection: closeHost: www.weather.com.cnAccept: text/xml,text/javascript,text/html,application/jsonContent-Type: application/jsonsocket 0, len 238[httpc][009130] httpc_send_request, connect 0[httpc][009160] httpc_send_request, send 238, ret 0[httpc][019170] on_message_begin, HTTP response (headers), method GET[httpc][019170] on_status, HTTP response status OK[httpc][019180] print_header_field, len 4, Date[httpc][019190] print_header_field, len 29, Wed, 09 Oct 2019 07:32:13 GMT[httpc][019200] print_header_field, len 12, Content-Type[httpc][019200] print_header_field, len 9, text/html[httpc][019210] print_header_field, len 17, Transfer-Encoding[httpc][019220] print_header_field, len 7, chunked[httpc][019220] print_header_field, len 10, Connection[httpc][019230] print_header_field, len 5, close[httpc][019240] print_header_field, len 6, Server[httpc][019240] print_header_field, len 9, openresty[httpc][019250] print_header_field, len 16, X-Xss-Protection[httpc][019260] print_header_field, len 1, 1[httpc][019260] print_header_field, len 10, Set-Cookie[httpc][019270] print_header_field, len 8, HttpOnly[httpc][019280] print_header_field, len 3, Age[httpc][019280] print_header_field, len 4, 2068[httpc][019290] print_header_field, len 5, X-Via[httpc][019300] print_header_field, len 125, 1.1 PSbjsdBGPvu28:10 (Cdn Cache Server V2.0), 1.1 zhdx147:10 (Cdn Cache Server V2.0), 1.1 huadxin69:7 (Cdn Cache Server V2.0)[httpc][019320] on_headers_complete, headers complete[httpc][019320] on_message_complete, HTTP GET response (complete)http session 20002298, buf size 4096 bytes, recv 578 bytes data[  19.340]sal_wifi HAL_SAL_Close 778 failed********************** weather data **********************{"weatherinfo":{"city":"杭州","cityid":"101210101","temp":"24.8","WD":"东北风","WS":"小于3级","SD":"81%","AP":"1000.3hPa","njd":"暂无实况","WSE":"<3","time":"17:50","sm":"2.1","isRadar":"1","Radar":"JC_RADAR_AZ9571_JB"}}**********************************************************

参考文档

AliOS Things 3.0 应用开发指南

使用AliOS Things3.0 快速构建用户应用BlinkAPP

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,841评论 5 472
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,415评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,904评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,051评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,055评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,255评论 1 278
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,729评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,377评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,517评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,420评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,467评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,144评论 3 317
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,735评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,812评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,029评论 1 256
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,528评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,126评论 2 341

推荐阅读更多精彩内容