在sqlite3数据库中读取gzipped字符串(python write,Java Android read)

Jos*_*ang 5 python java sqlite android gzip

我正在尝试通过压缩来最小化包含大量HTML的sqlite3数据库.我使用python来创建sqlite3数据库,我正在尝试在Android上正确解压缩.

我使用gzip压缩HTML并将数据库存储为BLOB.这是我为创建sqlite3 db(在Python中)编写的代码:

from sys import stdin, argv
import sqlite3
import gzip
import cStringIO

def compressBuf(buf):
    zbuf = cStringIO.StringIO()
    zfile = gzip.GzipFile(mode = 'wb',  fileobj = zbuf, compresslevel = 9)
    zfile.write(buf)
    zfile.close()
    return zbuf.getvalue()

conn = sqlite3.connect(argv[1])
conn.text_factory = str 
c = conn.cursor()

c.execute('''CREATE TABLE articles (
    id INTEGER NOT NULL PRIMARY KEY,
    name TEXT, category TEXT, html BLOB );''')

c.execute(' CREATE INDEX name_index on articles (name); ')

for line in stdin:
    line = line.strip().split('\t')
    line[-1] = sqlite3.Binary(compressBuf(line[-1]))    

    c.execute('INSERT INTO articles VALUES (?, ?, ?, ?);', line)

conn.commit()
c.close()
conn.close()
Run Code Online (Sandbox Code Playgroud)

以下是Android的代码段:

Cursor cursor = db.rawQuery("SELECT html FROM articles WHERE id = " + id + " limit 1;", null);
cursor.moveToFirst();
byte[] zhtml = cursor.getBlob(0);
ByteArrayInputStream is = new ByteArrayInputStream(zhtml);
GZIPInputStream gis = new GZIPInputStream(is, zhtml.length);
Run Code Online (Sandbox Code Playgroud)

我收到以下异常抱怨标头不正确:

 java.io.IOException: unknown format (magic number 213c)
   at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:84)
   at tw.cse.o0o.MyApp.WebServer$ArticleHandler$1.writeTo(WebServer.java:196)
   at org.apache.http.entity.EntityTemplate.writeTo(EntityTemplate.java:76)
   at org.apache.http.impl.entity.EntitySerializer.serialize(EntitySerializer.java:97)
   at org.apache.http.impl.AbstractHttpServerConnection.sendResponseEntity(AbstractHttpServerConnection.java:182)
   at org.apache.http.protocol.HttpService.handleRequest(HttpService.java:209)
   at tw.cse.o0o.MyApp.WebServer.run(SQLHelper.java:90)
Run Code Online (Sandbox Code Playgroud)

使用Python解释器,我可以确认函数compressBuf返回正确的gzip幻数0x1f8b:

>>> compressBuf('test')
'\x1f\x8b\x08\x00 \xba:O\x02\xff+I-.\x01\x00\x0c~\x7f\xd8\x04\x00\x00\x00'
Run Code Online (Sandbox Code Playgroud)

[编辑]

好的,这是我发现的:

在Nexus One上,我的getBlob()函数会自动解压缩二进制数据,无论是zlib还是gzip.错误日志中的213c是原始html的前两个字符.但是,三星Galaxy Tab(第一代)并非如此.我还在尝试在Galaxy Tab上找到解压缩的方法..

Joh*_*hin 0

'\x21\x3c-->>'!<'或者可能'<!'取决于字节顺序。我建议您调查(二进制)gzip 压缩数据在传输过程中被填充的可能性。