我正在尝试从服务器下载 gzip 压缩的 XML 文件,为此我使用以下代码:
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
HttpGet response = new HttpGet(urlData);
client.addRequestInterceptor(new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) {
// Add header to accept gzip content
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
}
});
client.addResponseInterceptor(new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext context) {
// Inflate any responses compressed with gzip
final HttpEntity entity = response.getEntity();
final Header encoding = entity.getContentEncoding();
if (encoding != null) {
for (HeaderElement element : encoding.getElements()) {
if (element.getName().equalsIgnoreCase("gzip")) {
response.setEntity(new InflatingEntity(response.getEntity()));
break;
}
}
}
}
});
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return client.execute(response, responseHandler);
InflatingEntity 方法:
private static class InflatingEntity extends HttpEntityWrapper {
public InflatingEntity(HttpEntity wrapped) {
super(wrapped);
}
@Override
public InputStream getContent() throws IOException {
return new GZIPInputStream(wrappedEntity.getContent());
}
@Override
public long getContentLength() {
return -1;
}
}
如果我删除与 Gzip 压缩相关的所有内容并用普通 XML 替换服务器中的压缩 XML 文件,一切正常,但在我实现 Gzip 压缩后,我得到了压缩字符串:
有谁知道我的代码中缺少什么来获取解压缩的 XML?