gpt4 book ai didi

c - 由于 HTTP header 中的奇怪字符,发送数据失败

转载 作者:太空宇宙 更新时间:2023-11-04 02:36:16 26 4
gpt4 key购买 nike

我使用以下代码创建了 hTTP header 并将其发送到服务器。然而,当它被接收时,它包含奇怪的字符。

 const char http_post_format[]=
{
"POST /%s HTTP/1.1\r\n\
Host: %s\r\n\
Content-Type: application/x-www-form-urlencoded\r\n\
Content-Length:%s\r\n\r\n\
%s\r\n"
};

代码片段如下:

 int client_fd = -1;
int len =- 1;
char *ipstr=(char*)malloc(16);
struct sockaddr_t addr;
char *content_length=(char*)malloc(20);
char *httpRequest = (char*)malloc(556);

// cs_log("Free memory has %d bytes", MicoGetMemoryInfo()->free_memory) ;
gethostbyname(http_host, (uint8_t *)ipstr, 16);
cs_log("server address: host:%s, ip: %s", http_host, ipstr);

client_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
addr.s_ip = inet_addr(ipstr);
addr.s_port = http_port;
connect(client_fd, &addr, sizeof(addr));

Int2Str((uint8_t*)content_length, strlen(str_args));

cs_log("content_length%s\n ",content_length);

sprintf(httpRequest, http_post_format,
http_post_url,
http_host,
content_length,
str_args);

len=write(client_fd,(uint8_t *)httpRequest, strlen(httpRequest));
if(len == -1){
memset(httpRequest,0,556);
}
cs_log("len%d\n%s\n ",len,httpRequest);

free(httpRequest);
httpRequest = NULL;
close(client_fd);
free(content_length);
content_length=NULL;
free(ipstr);
ipstr =NULL;

预期可以解析的http headers如下:

POST /sensor/sensorinfo HTTP/1.1 
Host: 192.168.199.218
Content-Type: application/x-www-form-urlencoded
Content-Length:240

info={ "WIFI_INFO": { "WIFI": { "connected": "1", "strength": "80", "ip": "192.168.199.131", "mac": "d0bae4075913", "ssid": "chaosuan" } }, "DHT11_INFO": { "DHT": { "T": "28", "H": "43" } }, "DSM501A_INFO": { "DSM501A": { "VALUE": "0" } } }

实际收到的数据在Content-Length中包含一些奇怪的字符。

POST /sensor/sensorinfo HTTP/1.1
Host: 192.168.199.218
Content-Type: application/x-www-form-urlencoded
Content-Length:240棍*橪馭嶲誳3

info={ "WIFI_INFO": { "WIFI": { "connected": "1", "strength": "74", "ip": "192.168.199.131", "mac": "d0bae4075913", "ssid": "chaosuan" } }, "DHT11_INFO": { "DHT": { "T": "28", "H": "43" } }, "DSM501A_INFO": { "DSM501A": { "VALUE": "0" } } }

这里是 Int2Str 函数

 void Int2Str(uint8_t* str, int32_t intnum)
{
uint32_t i, Div = 1000000000, j = 0, Status = 0;

for (i = 0; i < 10; i++)
{
str[j++] = (intnum / Div) + 48;

intnum = intnum % Div;
Div /= 10;
if ((str[j-1] == '0') & (Status == 0))
{
j = 0;
}
else
{
Status++;
}
}
}

最佳答案

你忘了在 Int2Str 中用 NUL 终止你的字符串:

这个函数的结尾应该是这样的:

   ...
{
Status++;
}
}

str[j] = 0; // <<< add this
}

免责声明:未经测试的代码,可能存在更多问题。

对了,你为什么要写Int2Stritoa或更标准的 strtol功能做同样的工作。

您甚至可以直接使用 sprintf%d 格式说明符,这样会更简单。

旁注

+ 48 不好。而是写 + '0',这样就没有人会猜测 48 是 '0' 字符的 ASCII 码。

关于c - 由于 HTTP header 中的奇怪字符,发送数据失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36864176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com