[文章]Hi3861 通过http get请求 获取当前时间

阅读量0
1
2

小熊派Hi3861,通过http get获取当前时间

完整代码:
*附件:http.zip

0、请求链接
使用淘宝api获取时间

http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp

1、定义请求头

static const char *Request = "GET /rest/api3.do?api=mtop.common.getTimestamp HTTP/1.1\\r\\n
Content-Type: application/json;charset=utf-8\\r\\n
Host: api.m.taobao.com\\r\\n
Connection: Keep Alive\\r\\n
\\r\\n";

const char addr_ip[] = "140.205.162.6";

3、定义函数

unsigned int http_clienti_get(void)
{
struct sockaddr_in addr = {0};
int s, r;
char recv_buf[HTTPC_DEMO_RECV_BUFSIZE];
addr.sin_family = AF_INET;
addr.sin_port = PP_HTONS(SOCK_TARGET_PORT);
addr.sin_addr.s_addr = inet_addr(addr_ip);
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0) {
return 1;
}
printf("... allocated socket");
if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
printf("... socket connect failed errno=%d", errno);
lwip_close(s);
return 1;
}
printf("... connected");
if (lwip_write(s, Request, strlen(Request)) < 0) {
lwip_close(s);
return 1;
}
printf("... socket send success");
struct timeval receiving_timeout;
/* 5S Timeout */
receiving_timeout.tv_sec = 5;
receiving_timeout.tv_usec = 0;
if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &receiving_timeout, sizeof(receiving_timeout)) < 0) {
printf("... failed to set socket receiving timeout");
lwip_close(s);
return 1;
}
printf("... set socket receiving timeout success");
/* Read HTTP response */
do {
(void)memset_s(recv_buf, sizeof(recv_buf), 0, sizeof(recv_buf));
r = lwip_read(s, recv_buf, sizeof(recv_buf) - 1);
for (int i = 0; i < r; i++) {

putchar(recv_buf[i]);
}
} while (r > 0);
printf("... done reading from socket. Last read return=%d errno=%d\\r\\n", r, errno);
lwip_close(s);
return 0;
}

4、接收数据展示

image.png

回帖

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容图片侵权或者其他问题,请联系本站作侵删。 侵权投诉
链接复制成功,分享给好友