c/c++的http协议的get和post方法

看看人家写的。

 

int sock;
struct sockaddr_in sin;

struct hostent *he=gethostbyname(Server);
if(!he)
{
return HTTP_UNKNOW_HOST;
}
sin.sin_family=he->;h_addrtype;
sin.sin_port = htons(m_port);
sin.sin_addr.s_addr=((unsigned long*)(he->;h_addr_list[0]))[0];

if((sock=socket(AF_INET,SOCK_STREAM,0))<0)
{
return HTTP_SOCKET_ERROR;
}
if(connect(sock,(struct sockaddr*)&sin,sizeof(sin))<0)
{
close(sock);
return HTTP_CONNECT_ERROR;
      

char str[4096];
sprintf(str,"GET %s HTTP/1.0\r\nHost:%s\r\nUser-Agent:Mozilla/4.0\r\n\r\n",query,(LPCSTR)m_host);
if(write(sock,str,strlen(str))<0)
{
close(sock);
return HTTP_WRITE_ERROR;
}

fd_set rfds;
struct timeval tv;

FD_ZERO(&rfds);
FD_SET(sock,&rfds);

tv.tv_sec=m_nSecs;
tv.tv_usec=0;

if(!select(sock+1,&rfds,NULL,NULL,&tv))
{
close(sock);
return HTTP_SELECT_ERROR;
      

if(FD_ISSET(sock,&rfds))
{
int        len=1024*4;
int i=0;
int rv=0;
char* buf=(char*)malloc((len+1)*sizeof(char));
while((rv=read(sock,buf,len)))
{
buf[rv] = 0 ;
m_content += buf ;
}
close(sock);
free(buf) ;

if(!m_content.IsEmpty())
{
if( m_content.Find("200")>;=m_content.Find("\n") ) {
return HTTP_UNKNOWN_ERROR;
}
if(m_pBody=(char*)m_content.Find("\r\n\r\n")) {
*m_pBody='\0';
m_pBody+=4;
} else if(m_pBody=(char*)m_content.Find("\n\n")) {
*m_pBody='\0';
m_pBody+=2 ;
} else {
return HTTP_BAD_HEADER;
}
return 0 ;
}
return HTTP_READ_ERROR ;
}
close(sock);
return HTTP_UNKNOWN_ERROR;

你可能感兴趣的:(Socket,WEB)