直接上函数代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
#include <afxwin.h> // MFC 核心组件和标准组件 #include <Wininet.h> #include <iostream> #include <string> using namespace std;
//walker 2013.05 //hostname主机名,例如www.baidu.com //suburl,例如asp/test.asp?num=3 //port,端口号 string GetHttpFile( const char hostname[], const char suburl[], unsigned short port)
{ HINTERNET hInternet = NULL,
hConnect = NULL,
hRequest = NULL;
BOOL bRtn;
string strResponse;
hInternet = InternetOpen( "User-Agent" ,INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL, 0 );
if (NULL == hInternet)
{
cout << "InternetOpen Failed!" << endl;
goto exception_over;
}
hConnect = InternetConnect(hInternet, hostname, port, NULL, " HTTP/1.1 " ,INTERNET_SERVICE_HTTP, 0 , 0 );
if (NULL == hConnect)
{
cout << "InternetConnect Failed!" << endl;
goto exception_over;
}
hRequest = HttpOpenRequest(hConnect, "GET" , suburl, " HTTP/1.1 " ,NULL,NULL,INTERNET_FLAG_RELOAD, 0 );
if (NULL == hRequest)
{
cout << "HttpOpenRequest Failed!" << endl;
goto exception_over;
}
//三种超时值
DWORD TimeOuts[] = {5*1000, 5*1000, 10*1000};
InternetSetOption(hRequest,INTERNET_OPTION_CONNECT_TIMEOUT , &(TimeOuts[0]), sizeof ( DWORD ));
InternetSetOption(hRequest,INTERNET_OPTION_SEND_TIMEOUT , &(TimeOuts[1]), sizeof ( DWORD ));
InternetSetOption(hRequest,INTERNET_OPTION_RECEIVE_TIMEOUT, &(TimeOuts[2]), sizeof ( DWORD ));
bRtn = HttpSendRequest(hRequest,NULL, 0 , NULL, 0);
if (!bRtn)
{
cout << "HttpSendRequest Failed!" << endl;
goto exception_over;
}
char buf[1000] = {0};
DWORD dwLengthBufQuery = sizeof (buf);
bRtn = HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH, buf, &dwLengthBufQuery, NULL);
if (!bRtn)
{
cout << "HttpQueryInfo Failed!" << endl;
goto exception_over;
}
int file_len = atoi (buf);
cout << "filelen: " << file_len << "bytes" << endl;
int i = 1;
const int BUF_LEN = 256;
char cReadBuffer[BUF_LEN] = {0};
unsigned long sum_recv = 0;
unsigned long read_len;
while (TRUE)
{
memset (cReadBuffer, 0 , BUF_LEN);
unsigned long lNumberOfBytesRead;
read_len = (file_len - sum_recv) > (BUF_LEN - 1) ? (BUF_LEN - 1) : (file_len - sum_recv);
bRtn = InternetReadFile(hRequest, cReadBuffer, read_len , &lNumberOfBytesRead);
//注意:这里认为文件中不会有'\0'
strResponse = strResponse + cReadBuffer;
cout << "第" << i << "次: " << lNumberOfBytesRead << "bytes" << endl;
if ( !bRtn || strResponse.size() >= (unsigned int )file_len)
{
break ;
}
++i;
}
exception_over: if (NULL != hRequest)
{
InternetCloseHandle(hRequest);
}
if (NULL != hConnect)
{
InternetCloseHandle(hConnect);
}
if (NULL != hInternet)
{
InternetCloseHandle(hInternet);
}
return strResponse;
} |
***
本文转自walker snapshot博客51CTO博客,原文链接http://blog.51cto.com/walkerqt/1206538如需转载请自行联系原作者
RQSLT