问一个关于使用wininet.lib的问题
我想写一个多线程下载的命令行程序。但是在使用wininet.lib提供的api函数时遇到了问题
源代码如下
#include "stdio.h"
#include "windows.h"
#include "wininet.h"
void usage();
LPTSTR GetFileName(LPCTSTR lpszFilePath);
void ShowError(LPCSTR lpszFuntionName);
int main(int argc,char *argv[])
{
HINTERNET hSession;
HINTERNET hConnect;
HINTERNET hRequest;
const CHAR *lpszAcceptTypes = "*/*" ;
CHAR szServername[256]="www.******.com";
CHAR szObjectname[100]="***.exe";
INTERNET_PORT wPort = 80;
LPTSTR lpszAgent = NULL;
lpszAgent = GetFileName(argv[0]);
hSession = InternetOpen(lpszAgent,INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);
if (hSession == NULL)
{
ShowError("InternetOpen");
return -1;
}
hConnect = InternetConnect(hSession,szServername,wPort/*INTERNET_DEFAULT_HTTP_PORT*/,NULL,NULL,INTERNET_SERVICE_HTTP,0,0);
if (hConnect == NULL)
{
ShowError("InternetConnect");
return -2;
}
hRequest = HttpOpenRequest(hConnect,"GET",szObjectname,NULL,NULL,&lpszAcceptTypes,INTERNET_FLAG_RELOAD,0);
if (hRequest == NULL)
{
ShowError("HttpOpenRequest");
return -3;
}
//CHAR szHttpHeader[256] = "Host: ***********\r\n";
//BOOL bRetSend = HttpSendRequest(hRequest,szHttpHeader,strlen(szHttpHeader),NULL,0);
BOOL bRetSend = HttpSendRequest(hRequest,NULL,0,NULL,0);
if (bRetSend == FALSE)
{
ShowError("HttpSendRequest");
return -4;
}
DWORD dwIndex=0;
CHAR szBuffer[32] = {0};
DWORD dwBufferLen=32;
BOOL bRetQueryInfo = HttpQueryInfo(hRequest,HTTP_QUERY_CONTENT_LENGTH,szBuffer,&dwBufferLen,&dwIndex);
DWORD dwFileSize = (DWORD)atol(szBuffer) ;
if (bRetQueryInfo == FALSE)
{
ShowError("HttpQueryInfo");
return -5;
}
//CreateThread()
}
void usage()
{
printf("Code by shocker<shocker@c4st.cn>");
printf("Usage:\n");
}
LPTSTR GetFileName(LPCTSTR lpszFilePath)
{
LPTSTR p;
p = strrchr(lpszFilePath, '\\');
if (p) {
p++;
}
else {
p = (CHAR *)lpszFilePath;
}
return p;
}
void ShowError(LPCSTR lpszFuntionName)
{
DWORD nError;
nError = GetLastError();
printf("%s Error! GetLastError return:%d\n",lpszFuntionName,nError);
}
但是不知道为什么,当我调用HttpQueryInfo(hRequest,HTTP_QUERY_CONTENT_LENGTH,szBuffer,&dwBufferLen,&dwIndex);这个时总是不能正确返回文件的大小,每次都返回20.....
我可以确定要下载的文件存在,并且路径没错