通过向服务器端发送get请求来让服务器端将其上的文件下载到客户端时间:2021-02-15 17:53:28紧接着上两篇关于文件流传递的demo,后来发现还是通过http的get请求,效果最好,可以很快的将服务器端的文件下载到客户端。代码如下所示: 首先我们写一个服务器端应用,它可以看成是一个servlet: package download; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class A */ public class ServerServlet extends HttpServlet { public static int BUFFER_SIZE = 1024 * 1024; static Runtime get_runtime = Runtime.getRuntime(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { usedMemory(1); File file = new File("E:/toodou_work/test.csv"); BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); //实现了一个输出流,其中的数据被写入一个 byte 数组。缓冲区会随着数据的不断写入而自动增长。可使用 toByteArray() 和 toString() 获取数据。 ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE); byte[] temp = new byte[BUFFER_SIZE]; int size = 0; //读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。 while ((size = in.read(temp)) != -1) { out.write(temp, 0, size); } usedMemory(2); in.close(); //Provides an output stream for sending binary data to the client. ServletOutputStream baos = response.getOutputStream(); out.writeTo(baos);// byte 数组输出流的全部内容写入到指定的输出流参数中,这与使用 out.write(buf, 0, count) 调用该输出流的 write 方法效果一样。 out.flush(); } public static void usedMemory(int i) { long l = get_runtime.totalMemory() - get_runtime.freeMemory(); long k = l / 1024; System.out.println(i + ": " + k + " K"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 客户端代码: package download; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class SendGetRequest { static String sessionId = ""; static Runtime send_runtime = Runtime.getRuntime(); public static void main(String[] args) throws Exception { ServerServlet.usedMemory(3); URL url = new URL("http://localhost:8080/abc/ServerServlet"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输入,则将 DoInput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 true。 connection.setDoOutput(true); // Read from the connection. Default is true. connection.setDoInput(true); // Set the post method. Default is GET connection.setRequestMethod("GET"); // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数 connection.setInstanceFollowRedirects(false); // connection. Settings above must be set before connect! // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的 // 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode // 进行编码 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("ENCTYPE", "multipart/form-data"); // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成, // 要注意的是connection.getOutputStream会隐含的进行connect。 connection.connect(); /*//记录发送请求时间 Long sendTime = System.currentTimeMillis(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); // 要传的参数 String content = URLEncoder.encode("sendTime", "UTF-8") + "=" + URLEncoder.encode(sendTime.toString(), "UTF-8"); //读海量文件 StringBuilder postStrBuf = new StringBuilder(); for (int i = 0; i < 1; i++) { File file = new File("E:/toodou_work/yuliang.csv"); BufferedReader reader = null; String postStr = null; reader = new BufferedReader(new FileReader(file)); while ((postStr = reader.readLine()) != null) { postStrBuf.append(postStr); } } content = content + "&" + URLEncoder.encode("file", "UTF-8") + "=" + URLEncoder.encode(postStrBuf.toString(), "UTF-8"); // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面 out.writeBytes(content); out.flush(); out.close(); // flush and close */ //记录发送请求时间 long start = System.currentTimeMillis(); //Get Session ID String key = ""; if (connection != null) { for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) { if (key.equalsIgnoreCase("set-cookie")) { sessionId = connection.getHeaderField(key); sessionId = sessionId.substring(0, sessionId.indexOf(";")); } } } InputStream is = connection.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); FileOutputStream fos = new FileOutputStream(new File("e:/1111111.txt")); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] temp = new byte[ServerServlet.BUFFER_SIZE]; int size = 0; while ((size = bis.read(temp)) != -1) { bos.write(temp, 0, size); } ServerServlet.usedMemory(4); bos.flush();//刷新此缓冲的输出流。这迫使所有缓冲的输出字节被写出到底层输出流中。 bos.close(); bis.close(); // BufferedReader br = new BufferedReader(new InputStreamReader(is)); // // String str = null; // StringBuilder sb = new StringBuilder(); // // while ((str = br.readLine()) != null) { // System.out.println(str); // } //记录将从连接请求返回的数据写到文件完毕的时间 /*long end = System.currentTimeMillis(); System.out.println("cost time: " + (end - start) + " ms");*/ //关闭连接 connection.disconnect(); } }