欢迎光临
我们一直在努力

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;
}
赞(4) 打赏
未经允许不得转载:huangea的博客 » LINUX C下实现HTTP POS请求并解析code码

评论 1

  1. #1

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

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

有趣的网站

支持快讯、专题、百度收录推送、人机验证、多级分类筛选器,适用于垂直站点、科技博客、个人站,扁平化设计、简洁白色、超多功能配置、会员中心、直达链接、文章图片弹窗、自动缩略图等...

联系我们联系我们

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

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册