Qt解决QUrl含有中文或特殊字符无法下载的问题

// url = http://www.xxx.com/xxx – 3 xxx.txt
void getRemoteFile(const QString url)
{
    // 解决文件名中含有特殊字符无法下载的问题
    QString fileName = QUrl(url).fileName();
    QString headPath = QString(url).remove(fileName);

    QTextCodec *codec = QTextCodec::codecForName("gbk");
    QByteArray byte = codec->fromUnicode(fileName);	// 只对文件名进行编码,否则前面路径会改变 http%3A%2F%2Fwww.xxx
    byte = byte.toPercentEncoding();	// 转成带百分号的格式
    byte = QByteArray(headPath.toStdString().c_str()) + byte;

    QUrl encodeUrl(byte);
    encodeUrl = encodeUrl.fromEncoded(byte);    // encodeUrl = http://www.xxx.com/xxx %A8C 3 xxx.txt
    m_reply = m_manager.get(QNetworkRequest(encodeUrl));
}

把转码后的字符转回

QString path = reply->url().toString().remove(m_remoteServerURL); // path = xxx %A8C 3 xxx.txt
QTextCodec *codec = QTextCodec::codecForName("gbk");

QByteArray ba = codec->fromUnicode(path);
ba = QByteArray::fromPercentEncoding(ba);

path =codec->toUnicode(ba); // path = xxx – 3 xxx.txt


 
 

版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(编码,中文,qt,Codec)