概述
HTTP返回GZIP内容的解压及中文显示
为节省流量,大部分的网页返回内容都会压缩后再传输,如果返回头包含Content-Encoding: gzip,那么必须 进行解压才能获取正确的返回值。下面基于QT实现解压网页返回内容,并转化为中文显示。
QT里面已经集成了zlib,可以利用zlib里面的函数实现解压,使用时需要包含 zlib.h头文件。
解压函数:
QByteArray uncompressGZip(const QByteArray &data)
{
if (data.size() <= 4)
{
qWarning("gUncompress: Input data is truncated");
return QByteArray();
}
QByteArray result;
int ret;
z_stream strm;
static const int CHUNK_SIZE = 1024;
char out[CHUNK_SIZE];
/* allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = data.size();
strm.next_in = (Bytef*)(data.data());
ret = inflateInit2(&strm, 15 + 32); // gzip decoding
if (ret != Z_OK)
return QByteArray();
// run inflate()
do {
strm.avail_out = CHUNK_SIZE;
strm.next_out = (Bytef*)(out);
ret = inflate(&strm, Z_NO_FLUSH);
Q_ASSERT(ret != Z_STREAM_ERROR); // state not clobbered
switch (ret) {
case Z_NEED_DICT:
ret = Z_DATA_ERROR; // and fall through
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
return QByteArray();
}
result.append(out, CHUNK_SIZE - strm.avail_out);
} while (strm.avail_out == 0);
// clean up and return
inflateEnd(&strm);
return result;
}
uncompressGZip函数返回的就是解压后的内容。
内容的中文显示:
大部分网页都会使用UTF-8对文件进行编码, 使用以下代码即可正常显示中文:
QTextCodec *codec = QTextCodec::codecForName("UTF8");
QTextCodec::setCodecForLocale(codec);
qDebug()<<codec->toUnicode(uncompress_content);
下面是另外两种中文编码,具体是哪种,可以查看下请求头的Content-Type:charset
//QTextCodec *codec = QTextCodec::codecForName("GBK");
//QTextCodec *codec = QTextCodec::codecForName("GB2312");
最后
以上就是害怕日记本为你收集整理的HTTP返回GZIP内容的解压及中文显示的全部内容,希望文章能够帮你解决HTTP返回GZIP内容的解压及中文显示所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复