2
我試圖下載一個XML文件是gzip的從服務器壓縮了,我用下面的代碼:Gzip已解壓縮返回隨機字符
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?
檢查xml在服務器上是否被解壓縮兩次...代碼看起來不錯,應該可以工作... – Selvin
看起來像一個嵌入文件名的壓縮數據流。確保壓縮源數據時確實發生gzip膨脹。 – fadden
@fadden是的,你是正確的,它不是解壓縮響應這是因爲這行:最終HttpEntity實體= response.getEntity();是空的,爲什麼會這樣? – BigBen3216