【问题标题】:gzip compression wont work with my custom java HTTP servergzip 压缩不适用于我的自定义 java HTTP 服务器
【发布时间】:2013-11-20 19:29:02
【问题描述】:

不知道我在这里做错了什么。当我尝试使用萤火虫查看响应时,它只是说我需要重新加载页面以获取它的来源。我尝试改用 GZIPOutputStream,但它只是在开头写了一些奇怪的字符,甚至没有产生有效的标题。

还尝试了其他一些随机的东西,但都没有任何帮助,所以通过反复试验和开明的 stackoverflow 智慧。

这怎么还抱怨我需要添加上下文?

嗯,我真的很累,而且我的编码技能已经退化到只是对着显示器大喊大叫。上下文如何?

哦,我正在使用的服务器是 NanoHTTPD 的一个 mod,我需要为此使用它。

private void sendResponse( String status, String mime, Properties header, InputStream data,boolean acceptEncoding)
    {
        try
        {
            if ( status == null )
                throw new Error( "sendResponse(): Status can't be null." );

            OutputStream out = mySocket.getOutputStream();

            PrintWriter pw = new PrintWriter( out );
            if(acceptEncoding){

                out = new java.util.zip.DeflaterOutputStream(out);//tried using GZIPInputStream here
                header.setProperty("Content-Encoding","deflate"); // and gzip here, worked even worse
            }


            pw.print("HTTP/1.1 " + status + " \r\n");

            if ( mime != null )
                pw.print("Content-Type: " + mime + "\r\n");

            if ( header == null || header.getProperty( "Date" ) == null )
                pw.print( "Date: " + gmtFrmt.format( new Date()) + "\r\n");

            if ( header != null )
            {
                Enumeration e = header.keys();
                while ( e.hasMoreElements())
                {
                    String key = (String)e.nextElement();
                    String value = header.getProperty( key );
                    pw.print( key + ": " + value + "\r\n");
                }
            }

            pw.print("\r\n");
            pw.flush();



            if ( data != null )
            {
                byte[] buff = new byte[2048];
                while (true)
                {
                    int read = data.read( buff, 0, 2048 );
                    if (read <= 0)
                        break;
                    out.write( buff, 0, read );
                }
            }
            out.flush();
            out.close();
            if ( data != null )
                data.close();
        }
        catch( IOException ioe )
        {
            // Couldn't write? No can do.
            try { mySocket.close(); } catch( Throwable t ) {}
        }
    }

【问题讨论】:

  • 尝试删除 Content-Length 和 Content-Range 标头参数,完全没有帮助。

标签: java http gzip http-compression nanohttpd


【解决方案1】:

当创建GZIPOutputStream 时,它会在构造函数中写入标题字节。由于您在写入 HTTP 标头之前创建了 GZIPOutputStream 实例,因此 GZip 标头在 HTTP 标头之前写入。您必须在完整编写 HTTP 标头后创建GZIPOutputStream

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-23
    • 2016-10-23
    • 1970-01-01
    • 2011-08-08
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多