我有从服务器加载视频文件的servlet,并将其作为http get请求的响应发送。下面是他的代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
System.out.println("Start of doGet");
FileSystemManager fsManager = null;
try {
fsManager = VFS.getManager();
} catch (FileSystemException e) {
e.printStackTrace();
}
// Get requested image by path info.
String requestedImage = request.getPathInfo();
// Check if file name is actually supplied to the request URI.
if (requestedImage == null) {
// Do your thing if the image is not supplied to the request URI.
// Throw an exception, or send 404, or show default/warning image, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
FileObject basePath;
try {
basePath = fsManager.resolveFile( imagePath + URLDecoder.decode(requestedImage, "UTF-8"));
} catch (FileSystemException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return;
}
String baseName = basePath.getName().getBaseName();
String contentType = getServletContext().getMimeType(baseName);
// Init servlet response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(basePath.getContent().getSize()));
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
int count = 0;
try {
// Open streams.
FileContent fc = basePath.getContent();
InputStream is = (InputStream) fc.getInputStream();
input = new BufferedInputStream(is, DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
count++;
}
System.out.println("no exception occurred");
}
catch(Exception e){
System.out.println("while did " + count + " iterations befor exception occurred");
System.out.println("Catched exception: " + e);
}
finally{
// Gently close streams.
System.out.println("closing streams");
close(input);
close(output);
}
}例如,当我在google chrome中启动http://localhost:8080/MyApp/video/VX-276.ogg时,我得到了以下输出:
doGet的开始
在发生异常之前是否进行了3次迭代
捕获的异常: ClientAbortException: java.net.SocketException:对等重置连接:套接字写入错误
关闭流
doGet的开始
在发生异常之前是否进行了4次迭代
捕获异常: ClientAbortException: java.net.SocketException:软件导致连接中止:套接字写入错误
关闭流
doGet的开始
doGet的开始
在发生异常之前是否进行了224次迭代
捕获的异常: ClientAbortException: java.net.SocketException:对等重置连接:套接字写入错误
关闭流
在发生异常之前是否进行了4次迭代
捕获异常: ClientAbortException: java.net.SocketException:软件导致连接中止:套接字写入错误
关闭流
doGet的开始
在发生异常之前是否进行了12次迭代
捕获异常: ClientAbortException: java.net.SocketException:软件导致连接中止:套接字写入错误
关闭流
我如何修复我的代码?
发布于 2013-01-17 06:09:29
没有人考虑过浏览器上的缓存问题。
在servlet的开头使用这行代码。
Response.addHeader(“缓存控制”,“无转换,最大年龄=0”);
https://stackoverflow.com/questions/5290200
复制相似问题