nclude
#include
#include
#include "../include/tuobao_tcpclient.h"
int http_post(tuobao_tcpclient *pclient,char *page,char *request,char **response){
char post[300],host[100],content_len[100];
char *lpbuf,*ptmp;
int len=0;
int err=0;
lpbuf = NULL;
const char *header2="User-Agent: Tuobao Http 0.1
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
Accept: */*
";
sprintf(post,"POST %s HTTP/1.0
",page);
sprintf(host,"HOST: %s:%d
",pclient->remote_ip,pclient->remote_port);
sprintf(content_len,"Content-Length: %d
",(int)strlen(request));
len = strlen(post)+strlen(host)+strlen(header2)+strlen(content_len)+strlen(request)+1;
lpbuf = (char*)malloc(len);
if(lpbuf==NULL){
return -1;
}
strcpy(lpbuf,post);
strcat(lpbuf,host);
strcat(lpbuf,header2);
strcat(lpbuf,content_len);
strcat(lpbuf,request);
if(!pclient->connected){
err=tuobao_tcpclient_conn(pclient);
if(err<0)
return -1;
}
if(tuobao_tcpclient_send(pclient,lpbuf,len)<0){
return -1;
}
printf("send request:
%s
",lpbuf);
/*释放内存*/
if(lpbuf != NULL) free(lpbuf);
lpbuf = NULL;
/*it's time to recv from server*/
if(tuobao_tcpclient_recv(pclient,&lpbuf,0) <= 0){
if(lpbuf) free(lpbuf);
return -2;
}
printf("receive repose:
%s
",lpbuf);
/*响应代码,|HTTP/1.0 200 OK|
*从第10个字符开始,第3位
* */
memset(post,0,sizeof(post));
strncpy(post,lpbuf+9,3);
if(atoi(post)!=200){
if(lpbuf) free(lpbuf);
return atoi(post);
}
ptmp = (char*)strstr(lpbuf,"
");
if(ptmp == NULL){
free(lpbuf);
return -3;
}
ptmp += 4;/*跳过
*/
len = strlen(ptmp)+1;
*response=(char*)malloc(len);
if(*response == NULL){
if(lpbuf) free(lpbuf);
return -1;
}
memset(*response,0,len);
memcpy(*response,ptmp,len-1);
/*从头域找到内容长度,如果没有找到则不处理*/
ptmp = (char*)strstr(lpbuf,"Content-Length:");
if(ptmp != NULL){
char *ptmp2;
ptmp += 15;
ptmp2 = (char*)strstr(ptmp,"
");
if(ptmp2 != NULL){
memset(post,0,sizeof(post));
strncpy(post,ptmp,ptmp2-ptmp);
if(atoi(post)
(*response)[atoi(post)] = '