工作中需要使用json.最后抓了报文,对比代码输出,才得以解决。在这里共享出来,给需要的朋友一点帮助。
需要整个代码的朋友,可以下载《C代码版本的HTTP POST上传文件/JSON》:
static int http_post(tcpclient *pclient, const char *page, const const char* message_json, int* ret_code, char **response) { char content_buffer[4096] = {0}; char post[512]={0}; char host[256]={0}; char* lpbuf = NULL; char* ptmp = NULL; const char *header2="Connection: keep-alive\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: python-requests/2.18.4\r\n"; sprintf(post,"POST %s HTTP/1.1\r\n",page); strcpy(content_buffer, post); sprintf(host,"HOST: %s:%d\r\n",pclient->remote_ip,pclient->remote_port); strcat(content_buffer, host); strcat(content_buffer, header2); char *lenstr; lenstr = (char*)GH_MEM_MALLOC(256); sprintf(lenstr, "%d", (int)(strlen(message_json))); strcat(content_buffer, "Content-Length: "); strcat(content_buffer, lenstr); strcat(content_buffer, "\r\n"); char content_type[4096] = {0}; strcat(content_type, "Content-Type: application/json"); strcat(content_type, "\r\n\r\n"); strcat(content_type, message_json); strcat(content_buffer, content_type); GH_MEM_FREE(lenstr); tcpclient_send(pclient, content_buffer, strlen(content_buffer)); }