URLDownloadToFile 下载中文路径文件时候,会出现http 404错误,原因是默认的编码格式与服务器不一致所致.因此需要修改url的编码.
由于服务器使用的是Tomcat 服务器,设置链接地址使用编码为UTF-8 ,修改方法为红色部分:
<Connector port="80" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8" />
使用URLDownloadToFil时候,需要将非英文字符换,例如:http://www.52youda.com/macUpdate/1/新建文件夹/新建文本文档.txt
转换为:
http://www.52youda.com/macUpdate/1/%E6%96%B0%E5%BB%BA%E6%96%87%E4%BB%B6%E5%A4%B9/%E6%96%B0%E5%BB%BA%E6%96%87%E6%9C%AC%E6%96%87%E6%A1%A3.txt
转换方法:
1.将url转换为UTF-8编码:
void UNICODE_TO_UTF8(CString pScoure,char *pDestion)
{
DWORD dwLength =WideCharToMultiByte(CP_UTF8,NULL,pScoure,-1,NULL,0,NULL,FALSE);
WideCharToMultiByte(CP_UTF8, 0, pScoure, -1, pDestion, dwLength,NULL,FALSE);
}
2.将转换后的utf-8编码循环,遇到不是英文字符的则进行编码,代码段:
{
static char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char *pString=new char[webFileName.GetLength()*sizeof(TCHAR)*3];
UNICODE_TO_UTF8(webFileName,pString);
int nLength=strlen(pString);
char pszEncode[2000];
ZeroMemory(pszEncode,2000);
int pos=0;
for( int i = 0; i < nLength; i++ )
{
unsigned char c = pString[i];
if( c > 0x20 && c < 0x7f ) // 数字或字母
{
pszEncode[pos] = c;
pos++;
}
else if( c == 0x20 ) // 包含空格
{
pszEncode[pos] = '+'; pos++;
}
else // 进行编码
{
pszEncode[pos] = '%'; pos++;
pszEncode[pos] = hex[c / 16]; pos++;
pszEncode[pos] = hex[c % 16]; pos++;
}
}
delete[]pString;
}
3.使用:
USES_CONVERSION;
DWORD re=URLDownloadToFile(NULL,A2T(pszEncode),(localFileName),0,NULL);
代码示例:
static BOOL DOWNFILE(CString localFileName,CString webFileName,long trueFileSize=0)
{
if(trueFileSize!=0)
{
CFile file;
if(file.Open(localFileName,CFile::modeRead))
{
ULONGLONG size= file.GetLength();
if(trueFileSize==size)
{
file.Close();
return TRUE;
}
}
}
if(trueFileSize==0)
{
CImage image;
image.Load(localFileName);
if(!image.IsNull())return TRUE;
}
if(webFileName.GetLength()==0)return FALSE;
static char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char *pString=new char[webFileName.GetLength()*sizeof(TCHAR)*3];
UNICODE_TO_UTF8(webFileName,pString);
int nLength=strlen(pString);
char pszEncode[2000];
ZeroMemory(pszEncode,2000);
int pos=0;
for( int i = 0; i < nLength; i++ )
{
unsigned char c = pString[i];
if( c > 0x20 && c < 0x7f ) // 数字或字母
{
pszEncode[pos] = c;
pos++;
}
else if( c == 0x20 ) // 包含空格
{
pszEncode[pos] = '+'; pos++;
}
else // 进行编码
{
pszEncode[pos] = '%'; pos++;
pszEncode[pos] = hex[c / 16]; pos++;
pszEncode[pos] = hex[c % 16]; pos++;
}
}
delete[]pString;
USES_CONVERSION;
DWORD re=URLDownloadToFile(NULL,A2T(pszEncode),(localFileName),0,NULL);
if (re== S_OK)
{
return TRUE;
}
else return FALSE;
}