1 /*
2 * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "hi_stdlib.h"
17 #include "lwip/sockets.h"
18 #include "lwip/netdb.h"
19 #include "app_http_client.h"
20 #define HTTPC_DEMO_RECV_BUFSIZE 64
21 #define SOCK_TARGET_PORT 80
22
23 static const char *g_request = "GET / HTTP/1.1\r\n\
24 Content-Type: application/x-www-form-urlencoded;charset=UTF-8\r\n\
25 Host: baidu.com\r\n\
26 Connection: close\r\n\
27 \r\n";
28
29 /*****************************************************************************
30 * Func description: demo for http get action
31 *****************************************************************************/
http_clienti_get(int argc,const char * argv[])32 unsigned int http_clienti_get(int argc, const char *argv[])
33 {
34 if ((argc != 1) || (argv == NULL)) {
35 return 1;
36 }
37 struct sockaddr_in addr = {0};
38 int s, r;
39 char recv_buf[HTTPC_DEMO_RECV_BUFSIZE];
40 addr.sin_family = AF_INET;
41 addr.sin_port = PP_HTONS(SOCK_TARGET_PORT);
42 addr.sin_addr.s_addr = inet_addr(argv[0]);
43 s = socket(AF_INET, SOCK_STREAM, 0);
44 if (s < 0) {
45 return 1;
46 }
47 printf("... allocated socket");
48 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
49 printf("... socket connect failed errno=%d", errno);
50 lwip_close(s);
51 return 1;
52 }
53 printf("... connected");
54 if (lwip_write(s, g_request, strlen(g_request)) < 0) {
55 lwip_close(s);
56 return 1;
57 }
58 printf("... socket send success");
59 struct timeval receiving_timeout;
60 /* 5S Timeout */
61 receiving_timeout.tv_sec = 5;
62 receiving_timeout.tv_usec = 0;
63 if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &receiving_timeout, sizeof(receiving_timeout)) < 0) {
64 printf("... failed to set socket receiving timeout");
65 lwip_close(s);
66 return 1;
67 }
68 printf("... set socket receiving timeout success");
69 /* Read HTTP response */
70 do {
71 (void)memset_s(recv_buf, sizeof(recv_buf), 0, sizeof(recv_buf));
72 r = lwip_read(s, recv_buf, sizeof(recv_buf) - 1);
73 for (int i = 0; i < r; i++) {
74 putchar(recv_buf[i]);
75 }
76 } while (r > 0);
77 printf("... done reading from socket. Last read return=%d errno=%d\r\n", r, errno);
78 lwip_close(s);
79 return 0;
80 }
81
82