Qt下UrlEncode/UrlDecode实现(GBK/UTF-8)
#include <string>
#include <iostream>
// URL encode
std::string UrlEncode(const std::string& dec) {
std::string enc = ("");
unsigned char ch = 0x00;
unsigned char* p = (unsigned char*)dec.c_str();
while (*p) {
ch = (unsigned char)*p;
if (*p == ' ') {
enc += '+';
}
else if (((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'))
|| strchr("-_.~!*'();:@&=+$,/?#[]", ch)) {
enc += *p;
}
else {
enc += '%';
enc += (unsigned char)(((unsigned char)(ch >> 4)) > 9 ? ((unsigned char)(ch >> 4)) + 55 : ((unsigned char)(ch >> 4)) + 48);
enc += (unsigned char)(((unsigned char)(ch % 16)) > 9 ? ((unsigned char)(ch % 16)) + 55 : ((unsigned char)(ch % 16)) + 48);
}
++p;
}
return enc;
}
// URL decode
std::string UrlDecode(const std::string& enc) {
char p[2] = { 0 };
std::string dec = ("");
char* cd = (char*)enc.c_str();
int i = 0, len = (int)enc.length();
for (i = 0; i < len; i++) {
memset(p, '\0', 2);
if (cd[i] != '%') {
dec += cd[i];
continue;
}
p[0] = cd[++i];
p[1] = cd[++i];
p[0] = p[0] - 48 - ((p[0] >= 'A') ? 7 : 0) - ((p[0] >= 'a') ? 32 : 0);
p[1] = p[1] - 48 - ((p[1] >= 'A') ? 7 : 0) - ((p[1] >= 'a') ? 32 : 0);
dec += (unsigned char)(p[0] * 16 + p[1]);
}
return dec;
}
Qt封装:
QString QtUrlDecode(QString strGbk)
{
return QString::fromLocal8Bit(UrlDecode(strGbk.toStdString()).c_str());
}
QString QtUrlDecodeUtf8(QString strGbk)
{
QTextCodec *utf8 = QTextCodec::codecForName("utf-8");
QTextCodec *gbk = QTextCodec::codecForName("gbk");
QString decText = utf8->fromUnicode(gbk->toUnicode(UrlDecode(strGbk.toStdString()).data()));
return decText;
}
void printBinary(char *p)
{
unsigned int i;
//打印其内容, char *
for(i=0;i<strlen(p);i++)
{
printf("%02x ",(unsigned char)p[i]);
}
printf("\n");
}
int test() {
QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForLocale(utf8);
QTextCodec* gbk = QTextCodec::codecForName("gbk");
std::string src = "sy188377169zd2你好";
std::string str_encode, str_decode;
QString strUnicode= utf8->toUnicode(src.data());
//2. unicode -> gbk, 得到QByteArray
QByteArray gb_bytes= gbk->fromUnicode(strUnicode);
str_encode= UrlEncode(gb_bytes.data());
QString str ="sy188377169zd2%C4%E3%BA%C3";
str_encode =str.toStdString();
str_decode = UrlDecode(str_encode);
std::cout << str_encode << std::endl;
std::cout << str_decode << std::endl;
return 0;
}