AliOS Things 3.0應(yīng)用筆記:http client簡單應(yīng)用

簡介:?AliOS Things 3.0版本新增加了httpc組件(http 客戶端組件)会放,httpc組件支持多種RESTful的API調(diào)用修壕,包括GET、POST损同、PUT翩腐、HEAD等,也支持https安全協(xié)議膏燃。


給AliOS Things一顆STAR(前往GitHub關(guān)注我們)

目錄

? ? ? ? ??簡介

? ? ? ? ??準(zhǔn)備工作

? ? ? ? ??創(chuàng)建應(yīng)用工程

? ? ? ? ??編寫應(yīng)用代碼

? ? ? ? ? ? ? ??添加http組件

? ? ? ? ? ? ? ??天氣API說明

? ? ? ? ? ? ? ??使用http組件

? ? ? ? ? ? ? ??完整源碼

? ? ? ? ? ??編譯運(yùn)行

? ? ? ? ? ?參考文檔

簡介

AliOS Things 3.0版本于9月27日在云棲大會(huì)正式發(fā)布茂卦,在新版本中帶來了全新的應(yīng)用開發(fā)框架,幫助用戶快速構(gòu)建自己的應(yīng)用组哩。使用戶可以更專注于自身應(yīng)用的開發(fā)等龙。

AliOS Things 3.0版本新增加了httpc組件(http 客戶端組件),httpc組件支持多種RESTful的API調(diào)用伶贰,包括GET蛛砰、POST、PUT黍衙、HEAD等泥畅,也支持https安全協(xié)議。

準(zhǔn)備工作

參考AliOS Things Environment Setup?和AliOS Things 3.0 應(yīng)用開發(fā)指南?搭建好AliOS Things 3.0的應(yīng)用開發(fā)環(huán)境琅翻。

創(chuàng)建應(yīng)用工程

參考AliOS Things 3.0 應(yīng)用開發(fā)指南 > AliOS Studio中創(chuàng)建應(yīng)用工程創(chuàng)建好你的應(yīng)用工程位仁。

本示例新建的應(yīng)用工程名稱為httpclient_app,選擇的開發(fā)板為developerkit方椎。

編寫應(yīng)用代碼

新建好的應(yīng)用工程文件如下面所示:

.httpclient_app├──.aos# AliOS Things 3.0 應(yīng)用工程描述├──.vscode# AliOS Studio 配置文件├── Config.in# Menuconfig 配置文件├── README.md# 應(yīng)用說明文檔├── aos.mk# 編譯文件├── app_main.c# 應(yīng)用示例代碼└── k_app_config.h# 內(nèi)核配置

添加http組件

aos-cube會(huì)自動(dòng)根據(jù)include的頭文件來自動(dòng)添加組件聂抢。

http組件需要用到全局宏:BUILD_AOS,所以需要在aos.mk中額外增加一個(gè)全局宏定義:

GLOBAL_DEFINES += BUILD_AOS

天氣API說明

本示例使用http組件辩尊,發(fā)送http get請(qǐng)求獲取天氣數(shù)據(jù),天氣的API是中國天氣網(wǎng)提供的API:http://www.weather.com.cn/data/sk/101210101.html康辑,其中101210101代表是杭州摄欲。

使用curl命令可以測(cè)試該API接口:

$ curl http://www.weather.com.cn/data/sk/101210101.html{"weatherinfo":{"city":"杭州","cityid":"101210101","temp":"24.8","WD":"東北風(fēng)","WS":"小于3級(jí)","SD":"81%","AP":"1000.3hPa","njd":"暫無實(shí)況","WSE":"<3","time":"17:50","sm":"2.1","isRadar":"1","Radar":"JC_RADAR_AZ9571_JB"}}%

或者也可以在瀏覽器打開該鏈接測(cè)試API接口。

使用http組件

本示例主要使用到了http如下接口疮薇,詳細(xì)的http對(duì)外提供的接口和參數(shù)說明請(qǐng)參考include/network/http/http.h

/* httpc 初始化 */int8_thttp_client_initialize(void);/* 創(chuàng)建一個(gè)httpc實(shí)例 */httpc_handle_thttpc_init(httpc_connection_t*settings);/* 銷毀一個(gè)httpc實(shí)例 */int8_thttpc_deinit(httpc_handle_thttpc);/* 發(fā)送http請(qǐng)求 */int8_thttpc_send_request(httpc_handle_thttpc,int8_tmethod,char*uri,constchar*hdr,constchar*content_type,constchar*param,uint16_tparam_len);/* 構(gòu)建http請(qǐng)求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);

完整源碼

本示例應(yīng)用的工程源碼點(diǎn)擊這里下載胸墙。

注意:需要更改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();}

編譯運(yùn)行

點(diǎn)擊編譯和燒錄按咒。運(yùn)行后迟隅,在串口日志最后面就能看的獲取到的天氣信息。

運(yùn)行效果:

[? 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":"東北風(fēng)","WS":"小于3級(jí)","SD":"81%","AP":"1000.3hPa","njd":"暫無實(shí)況","WSE":"<3","time":"17:50","sm":"2.1","isRadar":"1","Radar":"JC_RADAR_AZ9571_JB"}}**********************************************************

參考文檔

AliOS Things 3.0 應(yīng)用開發(fā)指南

使用AliOS Things3.0 快速構(gòu)建用戶應(yīng)用BlinkAPP

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市智袭,隨后出現(xiàn)的幾起案子奔缠,更是在濱河造成了極大的恐慌,老刑警劉巖吼野,帶你破解...
    沈念sama閱讀 221,406評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件校哎,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡瞳步,警方通過查閱死者的電腦和手機(jī)闷哆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,395評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來单起,“玉大人抱怔,你說我怎么就攤上這事∴值梗” “怎么了屈留?”我有些...
    開封第一講書人閱讀 167,815評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長括儒。 經(jīng)常有香客問我绕沈,道長,這世上最難降的妖魔是什么帮寻? 我笑而不...
    開封第一講書人閱讀 59,537評(píng)論 1 296
  • 正文 為了忘掉前任乍狐,我火速辦了婚禮,結(jié)果婚禮上固逗,老公的妹妹穿的比我還像新娘浅蚪。我一直安慰自己,他們只是感情好烫罩,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,536評(píng)論 6 397
  • 文/花漫 我一把揭開白布惜傲。 她就那樣靜靜地躺著,像睡著了一般贝攒。 火紅的嫁衣襯著肌膚如雪盗誊。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,184評(píng)論 1 308
  • 那天隘弊,我揣著相機(jī)與錄音哈踱,去河邊找鬼。 笑死梨熙,一個(gè)胖子當(dāng)著我的面吹牛开镣,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播咽扇,決...
    沈念sama閱讀 40,776評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼邪财,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼陕壹!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起树埠,我...
    開封第一講書人閱讀 39,668評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤糠馆,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后弥奸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體榨惠,經(jīng)...
    沈念sama閱讀 46,212評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,299評(píng)論 3 340
  • 正文 我和宋清朗相戀三年盛霎,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了赠橙。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,438評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡愤炸,死狀恐怖期揪,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情规个,我是刑警寧澤凤薛,帶...
    沈念sama閱讀 36,128評(píng)論 5 349
  • 正文 年R本政府宣布,位于F島的核電站诞仓,受9級(jí)特大地震影響缤苫,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜墅拭,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,807評(píng)論 3 333
  • 文/蒙蒙 一活玲、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧谍婉,春花似錦舒憾、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,279評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至唤蔗,卻和暖如春探遵,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背妓柜。 一陣腳步聲響...
    開封第一講書人閱讀 33,395評(píng)論 1 272
  • 我被黑心中介騙來泰國打工箱季, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人领虹。 一個(gè)月前我還...
    沈念sama閱讀 48,827評(píng)論 3 376
  • 正文 我出身青樓规哪,卻偏偏與公主長得像求豫,于是被迫代替她去往敵國和親塌衰。 傳聞我的和親對(duì)象是個(gè)殘疾皇子诉稍,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,446評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容