---
title: "httpclient 读取gzip网页"
author: "chenghuixy"
date: "2012-02-24T16:41:22Z"
tags: []
categories: ["编程语言"]
slug: "httpclient-gzip"
draft: false
lastmod: "2012-02-24T16:41:22Z"
id: 1422559
url: "https://liar.iteye.com/blog/1422559"
---

首先创建一个client对象：

```
DefaultHttpClient httpclient = new DefaultHttpClient();
```

 然后为这个client添加一个request拦截器和response拦截器

```
		httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
			public void process(final HttpRequest request,
					final HttpContext context) throws HttpException,
					IOException {
				if (!request.containsHeader("Accept-Encoding")) {
					request.addHeader("Accept-Encoding", "gzip");
				}
			}

		});

		httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
			public void process(final HttpResponse response,
					final HttpContext context) throws HttpException,
					IOException {
				HttpEntity entity = response.getEntity();
				Header ceheader = entity.getContentEncoding();
				if (ceheader != null) {
					HeaderElement[] codecs = ceheader.getElements();
					for (int i = 0; i < codecs.length; i++) {
						if (codecs[i].getName().equalsIgnoreCase("gzip")) {
							response.setEntity(new GzipDecompressingEntity(
									response.getEntity()));
							return;
						}
					}
				}
			}

		});
```

 然后访问会的内容就能正常显示了