欢迎光临
我们一直在努力

LINUX C下实现HTTP POS请求并解析code码

内容如题,本文主要实现 LINUX C下实现HTTP POS请求并解析code码

int post(char *ip,int port,char *page,char *msg){
  int code;
  char pos_status = -1;
  char post[256];
  int sockfd,n,recv_len,ctent_len;
  char recv_c;
  char *ptemp, *ptemp2;
  char recvline[MAXLINE];
  struct sockaddr_in servaddr;
  char content[4096];
  char content_page[50];
  sprintf(content_page,"POST /%s HTTP/1.1\r\n",page);
  char content_host[50];
  sprintf(content_host,"HOST: %s:%d\r\n",ip,port);
  char content_type[] = "Content-Type: application/x-www-form-urlencoded\r\n";
  char content_len[50];
  sprintf(content_len,"Content-Length: %d\r\n\r\n",strlen(msg));
  sprintf(content,"%s%s%s%s%s",content_page,content_host,content_type,content_len,msg);
  if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0)
    printf("socket error\n");
  bzero(&servaddr,sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_port = htons(port);
  if(inet_pton(AF_INET,ip,&servaddr.sin_addr) <= 0)
    printf("inet_pton error\n");
  while(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)) < 0)
  {
    printf("connect error\n");
    usleep(1000*3000);
    printf("reconnect...\n");
  }
  write(sockfd,content,strlen(content));
  int i = 0;
  pos_status = -1;
  while((n = read(sockfd,&recv_c,1)) > 0)
  {
    recvline[i++] = recv_c;
    if(recv_c == '}')
    {
      recvline[i] = '\0';
      ptemp = (char *)strstr(recvline,"Content-Length:");
      if(ptemp == NULL)
        continue;
      
      ptemp += 15;
      ptemp2 = (char *)strstr(ptemp,"\r\n");
      if(ptemp2 == NULL)
        continue;
      memset(post,0,sizeof(post));
      strncpy(post,ptemp,ptemp2-ptemp);
      ctent_len = atoi(post);
      if(i < ctent_len)
        continue;
      if(recvline[i - ctent_len] != '{')
        continue;
      
      pos_status = 1;
      memset(post,0,sizeof(post));
      strncpy(post,&recvline[i - ctent_len],ctent_len);
      printf("%s\n",post);
      break;
      
    }
    
  }
  
  if(pos_status < 0)
    return -3;
  char codes[10];
  ptemp = (char *)strstr(post,"\"code\":");
  if(ptemp == NULL)
    return -1;
  ptemp += 7;
  ptemp2 = (char *)strstr(post,"}");
  if(ptemp2 == NULL)
    return -1;
  recv_len = strlen(post);
  memset(codes,0,sizeof(codes));
  strncpy(codes,(const char *)ptemp,ptemp2 - ptemp);
  code = atoi(codes);
  printf("code = %d \n", code);
  
  return code;
}
赞(2) 打赏
未经允许不得转载:huangea的博客 » LINUX C下实现HTTP POS请求并解析code码
分享到: 更多 (0)

评论 1

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #1

    新年虽已过,好运不打折!

    营销软件3年前 (2018-03-06)回复

有趣的网站

联系我们联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏