日期:2014-05-20 浏览次数:21027 次
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = request.getParameter("url"); //得到要下载的资源的URL. if (!StringUtils.isNullOrEmpty(url)) { System.out.println(url); URL u = new URL(url); URLConnection conn = u.openConnection(); try { ///把响应头设置成一样的. for (Map.Entry<String, List<String>> m : conn.getHeaderFields() .entrySet()) { if (m != null && m.getKey() != null && m.getValue() != null && m.getValue().size() > 0) { response.setHeader(m.getKey(), m.getValue().get(0)); } } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); CommonLog.log.warn(e); } InputStream in = conn.getInputStream(); //从 connection得到inputstream OutputStream out = response.getOutputStream(); //得到向客户端的输出流 try { IOUtils .write(conn.getInputStream(), response .getOutputStream()); //写数据. } catch (Exception e) { e.printStackTrace(); // TODO: handle exception CommonLog.log.warn(e); if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
/** * 从input里面读取数据然后写入output,读完后自动关闭流。 * @param input inputStream * @param output outputStream * */ public static void write(InputStream input, OutputStream output) throws IOException { write(input,output,true); } /** * 自动从inputstream里面读数据,然后写到outputstream里面去。 * @param input inputstream * @param output outputstream * @param close 读完后是否自动关闭流。 * */ public static void write(InputStream input, OutputStream output,boolean close) throws IOException { byte[] b = new byte[1024]; int len = input.read(b); while (len != -1) { output.write(b, 0, len); len = input.read(b); } output.flush(); if (close) { input.close(); output.close(); } }
output.write(b, 0, len);//执行这行代码的时候.
ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error
at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:366)
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:432)
at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:347)
at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:392)