网络库百度一下就有,能用就行
,搬过来一个
int downloadURL(const char *host, unsigned short port, const char *path, string & body)
{
int sock;
struct sockaddr_in sin;
struct hostent *he = gethostbyname(host);
if (!he)
{
return HTTP_UNKNOW_HOST;
}
sin.sin_family = he->h_addrtype;
sin.sin_port = htons(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", path, 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 = 3;
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;
string content;
int rv = 0;
char buf[len + 1];
while ((rv = read(sock, buf, len)))
{
buf[rv] = 0;
content += buf;
}
close(sock);
if (!content.empty())
{
if (content.find("200") >= content.find("\n"))
{
return HTTP_UNKNOWN_ERROR;
}
int start = 0;
if (start = content.find("\r\n\r\n"))
{
body.append(content.c_str() + start + 4);
}
else if (start = content.find("\n\n"))
{
body.append(content.c_str() + start + 2);
}
else
{
return HTTP_BAD_HEADER;
}
return HTTP_SUCCESS;
}
return HTTP_READ_ERROR;
}
close(sock);
return HTTP_UNKNOWN_ERROR;
}
int downloadURL(const string & url, string & body)
{
int end = url.find("/");
string host = url.substr(0, end);
string path = url.substr(end);
return downloadURL(host.c_str(), 80, path.c_str(), body);
}