要从一个被屏蔽的网站上下载一些东西,于是写了一个Servlet,将它传到了一台境外的服务器上.
让这台服务器去下载指定的资源,然后再回传给我.相当于一个代理吧.
- Java code
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(); } } } }
IOUtils.write()代码如下:
- Java code
/** * 从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(); } }
将程序传到服务器上以后,在服务器上访问
http://localhost:8080/test/down?url=http://www.xxx.com/z.zip
可以下载成功.
但是当远程访问的时候,就会出现
java.net.SocketException: Connection reset by peer: socket write error
假设服务器IP是2.2.2.2吧.
访问
http://2.2.2.2:8080/test/down?url=http://www.xxx.com/z.zip
就会出现上面的那个错误.
注意,我并没有关闭浏览器或者按停止按钮.只要一打上那个地址就会出错.
错误发生在:
- Java code
output.write(b, 0, len);//执行这行代码的时候.
具体的错误信息如下:
- Java code
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)