winsock请求http

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了winsock请求http相关的知识,希望对你有一定的参考价值。

int socket_readline(SOCKET socket,char *head)  
{  
    char c = ‘\0‘;  
    int r = 0,i = 0;  
    while(recv(socket,&c,1,0)>0)  
    {  
        if(r == 1)  
        {  
            if(c == ‘\n‘)  
            {  
                break;  
            }  
            else  
            {  
                r = 0;  
            }  
        }  
        else if(c == ‘\r‘)  
        {  
            r = 1;  
        }  
        else head[i++] = c;  
    }  
    head[i] = ‘\0‘;  
    if(strcmp(head,"\r\n") == 0) return -1;  
    else return i;  
}  

int main(int argc, char* argv[])
{
	WSADATA wsaData;
	WORD sockVersion = MAKEWORD(2,0);
	WSAStartup(sockVersion,&wsaData);
	SOCKET s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(s==INVALID_SOCKET)
	{
		return -1;
	}
	sockaddr_in servAddr;
	servAddr.sin_family=AF_INET;
	servAddr.sin_port=htons(80);   
	servAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
	if(connect(s,(sockaddr*)&servAddr,sizeof(servAddr))==-1)
	{
		return -1;
	}

	char *httpHead = 
		"GET / HTTP/1.1\r\n"
		"Host: 127.0.0.1\r\n"  
        "Connection: Keep-Alive\r\n"  
		"\r\n";
	send(s,httpHead,strlen(httpHead),0);

	char *http_head_recv = new char[3000];  
    int Content_Length = 0;  
    for(int flag=1;flag>0;)  
    {  
        memset(http_head_recv,0,3000);  
        flag = socket_readline(s,http_head_recv);  
        if(strstr(http_head_recv,"Content-Length:") != NULL){  
            sscanf(http_head_recv,"Content-Length: %d",&Content_Length);  
        }  
        printf("%s\n",http_head_recv);  
    }  
    free(http_head_recv);

	if(Content_Length>0)
	{
		char *msg = new char[Content_Length+1];
		memset(msg,0,Content_Length+1);
		recv(s,msg,Content_Length,0);
		msg[Content_Length] = ‘\0‘;
		printf("%s\n",msg);
		free(msg);
	}

	closesocket(s);
	WSACleanup();
	return 0;
}

  

以上是关于winsock请求http的主要内容,如果未能解决你的问题,请参考以下文章

用VB的Winsock来发送http请求头,请指教!

使用 Winsock 接收分块的 HTTP 数据

如何使用http和winsock加载网页?

简单的 Javascript http 请求片段但不起作用

Qt (Creator) 与 WinSocks (ws2_32)

如何用UDP 实现服务器广播发送,并接收客户端点对点回复,用winsock实现,写出关键代码,谢谢~