Hello everyone,
I'm currently working on my home automation project.
the project required me to write my own "simple" webserver.
i have some code to detect that the webbrowser accepts gzip encoding.
if the browser supports it, i return gzip encoded websites but they seem to be rubbish since my browser (chrome) can't seem to display them.
public byte[] getHTTPPage(HTTPRequestHandler request, String name, Hashtable<String, String> headers, Hashtable<String, String> parameters) throws UnsupportedEncodingException, IOException { if (CacheManager.getInstance().isCached(name, HTTPServer.getSessionID(parameters))) { return CacheManager.getInstance().getCache(name, HTTPServer.getSessionID(parameters)).getData(); } else { BufferedReader reader = null; ByteArrayOutputStream bout = new ByteArrayOutputStream(); InputStream resource; BufferedInputStream input = null; boolean isImage = false; boolean useGZip = false; useGZip = HTTPServer.isGZipEnabled(headers); if (name.endsWith(".do")) { return HTTPServer.toByteArray(_generateHTTPPage(request, name, parameters)); } else if (this.getClass().getResource(resourceLocation + name) == null) { return new byte[0]; } try { resource = this.getClass().getResourceAsStream(resourceLocation + name); if (!isImage(name)) { reader = new BufferedReader(new InputStreamReader(resource)); while (reader.ready()) { if (!isImage) { bout.write(HTTPServer.toByteArray(reader.readLine() + "\r\n")); } else { bout.write(HTTPServer.toByteArray(reader.readLine())); } } } else { byte[] buffer = new byte[1024]; input = new BufferedInputStream(resource); int length = -1; while ((length = input.read(buffer, 0, buffer.length)) > -1) { bout.write(buffer, 0, length); } } } catch (FileNotFoundException ex) { ex.printStackTrace(); return null; } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { } try { if (input != null) { input.close(); } } catch (IOException ex) { } if (useGZip) { ByteArrayOutputStream temp = new ByteArrayOutputStream(); temp.write(HTTPServer.encodeToGZip(bout.toByteArray())); bout.reset(); bout.write(temp.toByteArray()); temp.reset(); temp = null; } CacheManager.getInstance().cache(name, bout.toByteArray(), HTTPServer.getSessionID(parameters)); return bout.toByteArray(); } } } public static byte[] encodeToGZip(byte[] data) { ByteArrayOutputStream bos = null; GZIPOutputStream output = null; try { bos = new ByteArrayOutputStream(); output = new GZIPOutputStream(bos); output.write(data); output.finish(); output.close(); //output.write(Base64.encodeBase64(data)); return Base64.encodeBase64(bos.toByteArray()); // return bos.toByteArray(); } catch (IOException ex) { ex.printStackTrace(); } //return bos.toByteArray(); return null; } public static byte[] toByteArray(String data) throws UnsupportedEncodingException { return data.getBytes("utf-8"); }
i'm not sure why it doesn't work.