0

不知道我在这里做错了什么。当我尝试使用萤火虫查看响应时,它只是说我需要重新加载页面以获取它的来源。我尝试使用 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 ) {}
        }
    }
4

1 回答 1

3

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

于 2013-11-20T20:14:42.750 回答