100 lines
2.2 KiB
C
100 lines
2.2 KiB
C
#include "http_client.h"
|
|
#include "stdio.h"
|
|
|
|
#define HTTP_SOCKET 0 // 使用Socket 0
|
|
|
|
// 直接使用IP地址的HTTP GET请求
|
|
http_result http_get_ip(const uint8_t* ip, uint16_t port, const char* path, http_response* response)
|
|
{
|
|
int32_t ret;
|
|
char request[512];
|
|
|
|
// 1. 创建socket
|
|
if((ret = socket(HTTP_SOCKET, Sn_MR_TCP, 0, 0)) != HTTP_SOCKET)
|
|
{
|
|
return HTTP_ERROR_SOCKET;
|
|
}
|
|
|
|
// 2. 连接服务器
|
|
if((ret = connect(HTTP_SOCKET, (uint8_t*)ip, port)) != SOCK_OK)
|
|
{
|
|
close(HTTP_SOCKET);
|
|
return HTTP_ERROR_CONNECTION;
|
|
}
|
|
|
|
// 3. 构建并发送HTTP请求
|
|
sprintf(request,
|
|
"GET %s HTTP/1.1\r\n"
|
|
"Host: %d.%d.%d.%d\r\n"
|
|
"Connection: close\r\n"
|
|
"\r\n",
|
|
path, ip[0], ip[1], ip[2], ip[3]);
|
|
|
|
if(send(HTTP_SOCKET, (uint8_t*)request, strlen(request)) <= 0)
|
|
{
|
|
close(HTTP_SOCKET);
|
|
return HTTP_ERROR_SEND;
|
|
}
|
|
|
|
// 4. 接收响应数据
|
|
response->length = 0;
|
|
while(1)
|
|
{
|
|
if(getSn_SR(HTTP_SOCKET) == SOCK_CLOSED) break;
|
|
|
|
ret = recv(HTTP_SOCKET,
|
|
&response->buffer[response->length],
|
|
HTTP_BUFFER_SIZE - response->length);
|
|
|
|
if(ret <= 0) break;
|
|
response->length += ret;
|
|
|
|
if(response->length >= HTTP_BUFFER_SIZE) break;
|
|
}
|
|
|
|
// 5. 关闭socket
|
|
close(HTTP_SOCKET);
|
|
|
|
if(response->length == 0)
|
|
{
|
|
return HTTP_ERROR_RECEIVE;
|
|
}
|
|
|
|
return HTTP_OK;
|
|
}
|
|
|
|
// URL解析函数
|
|
void parse_url(const char* url, char* host, char* path, uint16_t* port)
|
|
{
|
|
char* p;
|
|
|
|
// 跳过 "http://"
|
|
if(strncmp(url, "http://", 7) == 0)
|
|
url += 7;
|
|
|
|
// 复制主机名
|
|
p = strchr(url, '/');
|
|
if(p == NULL)
|
|
{
|
|
strcpy(host, url);
|
|
strcpy(path, "/");
|
|
}
|
|
else
|
|
{
|
|
strncpy(host, url, p - url);
|
|
host[p - url] = '\0';
|
|
strcpy(path, p);
|
|
}
|
|
|
|
// 检查端口号
|
|
p = strchr(host, ':');
|
|
if(p != NULL)
|
|
{
|
|
*p = '\0';
|
|
*port = atoi(p + 1);
|
|
}
|
|
else
|
|
{
|
|
*port = 80;
|
|
}
|
|
}
|