HTTP客户端
html:超文本标记协议
http:超文本文档传输协议
url:统一资源定位符
功能分析:
模拟Http协议,访问百度 http://www.baidu.com/index.html
串口打印出百度返回的信息
http服务器通讯过程模拟,加深理解http的交互过程
网而显示百度页面,这样就在本地模拟了一下http的通讯过程.
实现过程
实现代码
const char GetStr[] = "GET /index.html HTTP/1.1\r\n"
"Host: www.baidu.com\r\n"
"\r\n";
#define HTTP_RCV_LEN 50000
void ATaskHttpClient(void *pvParameters)
{
int iVariableExample = 0;
int fd = -1;
int NetTimerOut = 5000;
int ret, i;
struct sockaddr_in serverAddr;
char *Httpmsg;
struct hostent *phostent;
char *ipaddr = NULL;
STATION_STATUS StaStatus;
do
{
StaStatus = wifi_station_get_connect_status();
vTaskDelay(100);
} while (StaStatus != STATION_GOT_IP);
fd = socket(PF_INET, SOCK_STREAM, 0);
if (fd == -1)
{
printf("get socket fail!\n");
vTaskDelete(NULL);
return;
}
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &NetTimerOut, sizeof(int));
/*添加获取域名*/
phostent = gethostbyname("www.baidu.com");
if(phostent == NULL)
{
printf("get host ip fail!\n");
vTaskDelete(NULL);
return;
}
else
{
for(i=0; phostent->h_addr_list[i]; i++)
{
ipaddr = inet_ntoa(*(struct in_addr *)(phostent->h_addr_list[i]));
if(ipaddr != NULL)
{
printf("host addr is: %s\n", ipaddr);
break;
}
}
if(ipaddr == NULL)
{
printf("error:get ip fail!\n");
vTaskDelete(NULL);
return;
}
}
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr(ipaddr);
serverAddr.sin_port = htons(80);
serverAddr.sin_len = sizeof(serverAddr);
//连接到服务端
do
{
/* code */
ret = connect(fd, (struct sockaddr *)&serverAddr, serverAddr.sin_len);
if (ret != 0)
{
printf("Connect is fail!\n");
vTaskDelay(100);
}
} while (ret != 0);
Httpmsg = zalloc(HTTP_RCV_LEN);
send(fd, GetStr, strlen(GetStr), 0);
for (;;)
{
do
{
ret = recv(fd, Httpmsg, HTTP_RCV_LEN, 0);
if (ret > 0)
{
printf("HttpServer:%s\n", Httpmsg);
}
else
{
printf("HttpServer data is no!\n");
/* code */
}
vTaskDelay(100);
} while (ret == -1);
}
free(Httpmsg);
vTaskDelete(NULL);
}
void HttpClient_int(void)
{
xTaskCreate(ATaskHttpClient, "Httpclient", 256, NULL, 4, NULL);
}
串口数据