【发布时间】:2011-05-03 18:01:44
【问题描述】:
我使用 Java 套接字编程编写了一个简单的服务器,并打算让它提供 2 个文件供下载,并在下载完成时显示一些 html 响应。我所做的是使用 PrintWriter.print 或 DataOutPutStream.writeBytes 将包含 html 标签和响应字符串的字符串发送到浏览器,然后使用 OutputStream.write 发送请求的文件。我在浏览器中输入的网址是127.0.0.1/test1.zip,相关代码片段如下:
pout.print("<html>");
pout.print("<head>");
pout.print("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1/\">");
pout.print("<title>Response</title>");
pout.print("</head>");
pout.print("<body>");
pout.print(createResponseHeader(200, fileTypeCode));
pout.print("</body>");
pout.print("</html>");
pout.print(createResponseHeader(200, fileTypeCode));
pout.flush();
byte[] buffer = new byte[client.getSendBufferSize()];
int bytesRead = 0;
System.out.println("Sending...");
while((bytesRead = requestedFile.read(buffer))>-1)
{
out.write(buffer,0,bytesRead);
}
pout 是 PrintWriter,而 out 是 OutputStream。 问题是当我尝试使用 127.0.0.1/test2.zip 下载文件时,它不允许我下载,而是在浏览器中打印出响应字符串和很多无意义的字符,例如
HTTP/1.0 200 正常
连接:关闭
服务器:COMP5116 分配服务器 v0
内容类型:application/x-zip-compressed
PK‹â:Lmá^ЛàÍ test2.wmvì[y™îÝ+½Žö6A€;;ýmüH»êt©k]R#*€.G‰µÅRÏøÍLÔóZ; ´£åÑvP¹æª@õó”æÇ„(‹&‡ëî9q‰ÌÆÖ>LkÇÈ2 ãDŸã©ïÍš]Ð4iIJ0Àª3]B€ðÀ¸CôÁ`ä è1ü½¤ã¬$ pBi
我相信它只是将 zip 文件显示为带有响应标头的字符串。似乎一旦在发送文件的代码之前使用了 PrintWriter,整个输出流就用于发送字符串而不是字节。但是,如果我将发送响应的部分代码放在发送文件的代码之后,则下载正常,但浏览器中没有打印出任何响应消息,只是一个空白页。
【问题讨论】:
标签: java html sockets outputstream printwriter