Tomcat6设置gzip压缩 Java解压缩gzip
Tomcat的配置文件conf/server.xml添加如下的后四个属性即可设置将资源进行gzip压缩,有效提高响应速度:
connectionTimeout="20000"
redirectPort="8443"
compression="on"
compressionMinSize="2048"
noCompressionUserAgents="gozilla,traviata" compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain,image/gif,image/jpeg,image/png" />
利用http://gzip.zzbaike.com/ 测试,出现404 Not found错误好吧,自己测试搜的别人的代码:
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
public class HttpTester {
public static void main(String[] args) throws Exception{
HttpClient http = new HttpClient();
GetMethod get = new GetMethod("http://www.baidu.com/");
try{
get.addRequestHeader("accept-encoding", "gzip,deflate");
get.addRequestHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Alexa Toolbar; Maxthon 2.0)");
int er = http.executeMethod(get);
if(er==200){
System.out.println(get.getResponseContentLength());
String html = get.getResponseBodyAsString();
System.out.println(html);
System.out.println(html.getBytes().length);
}
}finally{
get.releaseConnection();
}
}
}
要想编译运行这段代码,必须引入3个包:commons-httpclient-3.0.1.jar commons-logging-1.1.1.jar 和 commons-codec-1.4.jar
并且String html = get.getResponseBodyAsString(); 最好替换为 InputStream is = get.getResponseBodyAsStream();然后再处理这个输入流(可以利用ByteArrayBuffer,但是需要引入httpcore-4.1.jar也可以不用,反正各种方法)
另一种测试方法,利用基本的J2SE,不用引入任何第三方包,也是搜的别人的:
public class Test2 {
public static void main(String[] args) {
try {
URL url = new URL("http://www.baidu.com/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Accept-Encoding", "gzip,deflate");//如果这里不设置,返回的就不是gzip的数据了,也就不用解压缩了
conn.connect();
InputStream in = conn.getInputStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in,"GB2312"));
//GZIPInputStream gzin = new GZIPInputStream(in);
// BufferedReader bin = new BufferedReader(new InputStreamReader(gzin, "GB2312"));
String s = null;
while((s=bin.readLine())!=null){
System.out.println(s);
}
bin.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
解压缩就是上面注释掉的两行代码