C语言采用socket实现http post方式上传json数据

1.按照HTTP协议发送请求:
http POST 报文格式
http 报文是面向文本的。
报文分为:请求报文和响应报文
请求报文由:请求行请求头部空行请求数据四个部分组成。
<1.请求行>POST:当客户端给服务器提供信息较多时可以使用POST方法,POST方法将请求参数封装在HTTP请求数据中,以名称/值的形式出现,可以传输大量数据,可用来传送文件。
<2.请求头部>:
由关键字/值对组成,每行一对,用:分隔,请求头部通知服务器有关于客户端请求的信息
典型的请求头有: User-Agent,Accept,Host,content-Type,Content-Length;.
<3.空行> :
最后一个请求头之后是一个空行,发送回车符和换行符,通知服务器以下不再有请求头。 对于一个完成的Http请求来说,空行是必须的,否则服务器会认为本次请求的数据尚未完全发送到服务器,处于等待状态。
<4.请求数据> :
POST方法适用于需要客户填写表单的场合,与请求数据相关的最常用的请求头是content-Type和Content-Length;

例子:
POST URL HTTP/1.1
HTTP若干选项
空行
POST数据段(以 分隔)

http报文头:
char *header = “POST / HTTP/1.1 ”
“Host: 192.168.9.20:8080 ”
“Content-Length: 62 ”
“AuthenticateUser=UserID&AuthenticatePassword=PWD&Submit= ”;

2.需求:
设备端触发事件,推送消息API
/icp/mesger.html?did=xx&dname=xx&dsname=xx&etype=xxx
did --->设备id号
dname --->内机名称
dsname --->外机名称
etype --->触发事件的类别

范例:
http://push.iotcare.cn/icp/mesger.html?did=AIOT-000001-DTFBR&dname=别墅1&dsname=大门&etype=0

3.软件实现:

snprintf(tmpBuf, sizeof(tmpBuf), "did=%s&dname=%s&dsname=%s&etype=%d&dsIndex=%d",
  pMsgInfo->szId,
  pMsgInfo->dname,
  pMsgInfo->dsname,
  pMsgInfo->eType,
  pMsgInfo->dsIndex);

snprintf(pOutBuf, sendLen, "POST /icp/mesger.html HTTP/1.1
" /*<1>.请求行*/
  "Host: %s:%d
" /*<2>.请求头部*/
  "Content-Type: application/x-www-form-urlencoded
"
  "Content-Length: %d
"
  "
" /*<3>.空行*/ 
  "%s", /*<4>.请求数据*/
  pAddr, 
  PUSH_SERV_PORT,
  strlen(tmpBuf),
  tmpBuf);

printf("send len:%d, cmd:
%s
", strlen(pOutBuf), pOutBuf);

4.测试结果:
POST /icp/mesger.html HTTP/1.1
Host: 47.74.191.223:80
Content-Type: application/x-www-form-urlencoded
Content-Length: 59

did=AIOT-000001-DTFBR&dname=RF&dsname=111&etype=5&dsIndex=0

 

参考文章:https://blog.csdn.net/mikewu_helloworld/article/details/52781675

原文地址:https://www.cnblogs.com/liudeen/p/10154461.html