最近做了一下WINNET的研究,有一些心得和大家分享一下。
我们先看看其相关的一些函数:
1)InternetOpen;
2)InternetOpenUrl;
3)HttpQueryInfo;
4)InternetReadFile;
5)InternetCloseHandle。
上面是同步的函数,在第2步和第4步,程序会一直等待,直到函数返回。如果要设置超时,可以使用InternetSetOption(不过好像没什么用)。在很多时候,这个函数是不合适的。比如用户主动要中断下载,却只能等待函数返回。还有,如果是大文件下载,无法想像一次读取上兆字节的数据,需使用断点续传,虽然也可以使用同步函数InternetSetFilePointer来定位网络文件读取位置,但很多服务器是支持的。如果在手机上使用,还要考虑诸如移动网关的限制等等。
1)InternetOpen,需指定是异步;
2)InternetSetStatusCallback,设置回调;
3)InternetOpenUrl,需指定回调参数;
4)WaitForSingObject或WaitForMultipleObjects,接收信号量;
5)HttpQueryInfo;
6)InternetReadFileEx,需指定回调参数;
7)WaitForSingObject或WaitForMultipleObjects,接收信号量;
8)InternetSetStatusCallback,卸载回调;
9)InternetCloseHandle。
这个也比较好理解,相当于需要设置回调函数,由回调处理,这个微软有例子。
void __stdcall Callback(HINTERNET hInternet,
DWORD dwContext,
DWORD dwInternetStatus,
LPVOID lpStatusInfo,
DWORD dwStatusInfoLen)
{
cout << "Callback dwInternetStatus: " << dwInternetStatus << " Context: " << dwContext << endl;
cout.flush();
switch(dwContext)
{
case 1: // Connection handle
if (dwInternetStatus == INTERNET_STATUS_HANDLE_CREATED)
{
INTERNET_ASYNC_RESULT *pRes = (INTERNET_ASYNC_RESULT *)lpStatusInfo;
hConnect = (HINTERNET)pRes->dwResult;
cout << "Connect handle created" << endl;
cout.flush();
SetEvent(hConnectedEvent);
}
break;
case 2: // Request handle
switch(dwInternetStatus)
{
case INTERNET_STATUS_HANDLE_CREATED:
{
INTERNET_ASYNC_RESULT *pRes = (INTERNET_ASYNC_RESULT *)lpStatusInfo;
hRequest = (HINTERNET)pRes->dwResult;
cout << "Request handle created" << endl;
cout.flush();
}
break;
case INTERNET_STATUS_REQUEST_SENT:
{
DWORD *lpBytesSent = (DWORD*)lpStatusInfo;
cout << "Bytes Sent: " << *lpBytesSent << endl;
dwNumBytesComplete += *lpBytesSent;
}
break;
case INTERNET_STATUS_REQUEST_COMPLETE:
{
INTERNET_ASYNC_RESULT *pAsyncRes = (INTERNET_ASYNC_RESULT *)lpStatusInfo;
cout << "Function call finished" << endl;
cout << "dwResult: " << pAsyncRes->dwResult << endl;
cout << "dwError: " << pAsyncRes->dwError << endl;
cout.flush();
SetEvent(hRequestCompleteEvent);
}
break;
case INTERNET_STATUS_RECEIVING_RESPONSE:
cout << "Receiving Response" << endl;
cout.flush();
break;
case INTERNET_STATUS_RESPONSE_RECEIVED:
{
DWORD *dwBytesReceived = (DWORD*)lpStatusInfo;
cout << "Received " << *dwBytesReceived << endl;
cout.flush();
}
}
}
}
这个也比较好理解,dwContext是1的时候连接的句柄,2的时候是请求的句柄,在2的时候也有CREATE,END,SEND,和REQUEST的几种状态。