项目中遇到问题总结一下:
在使用HttpURLConnection 上传大文件时,出现内存溢出的错误,这让我产生了错觉,输入和输出流咋会暂用内存,不就是一个数据传送的管道么,都没有把数据读取到内存中,为撒会报错。。。然后就纠结了。。。
不过实在与原来的经验相违背,然后写了一个示例直接从file中读出然后写入到输出流中,发现并没有问题
这下确认了问题出在HttpURLConnection,查看API发现,HTTP会有缓冲机制,缓存把JVM撑挂了导致内存溢出了。。。。
通过设置以下方法即可解决问题
setFixedLengthStreamingMode
public void setFixedLengthStreamingMode(int contentLength)
-
此方法用于在预先已知内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
如果应用程序尝试写入的数据多于指示的内容长度,或者应用程序在写入指示的内容长度前关闭了 OutputStream,将抛出异常。
启用输出流时,不能自动处理验证和重定向。如果需要验证和重定向,则在读取响应时将抛出 HttpRetryException。可以查询此异常以获取错误的详细信息。
该方法必须在连接 URLConnection 前调用。
- private void uploadFile()
- {
- String urlResouce = null;
- // urlResouce = "http://localhost:8080/application_interface_manager/platform/wangpan/444.png";
- urlResouce = "http://localhost:8080/application_interface_manager/platform/wangpan/myeclipse111.exe";
- try{
- // File localFile = new File("C:\\Users\\maomao\\Documents\\111.png");
- File localFile = new File("Z:\\tools\\myeclipse-8.5.0-win32.exe");
- //创建客户端签名
- String clientToken = new CreateSignTokenImpl().getToken("caizhonghu",secretKey);
- HttpURLConnection urlConnection =
- (HttpURLConnection) (new URL(urlResouce)).openConnection();
- urlConnection.setChunkedStreamingMode(0);
- urlConnection.setRequestProperty("Charset", "UTF-8");
- urlConnection.setRequestProperty("Token", "jingdong "+accessKey+":"+clientToken);
- urlConnection.setDoInput(true);
- urlConnection.setDoOutput(true);
- urlConnection.setRequestMethod("PUT");
- OutputStream urlOutputStream = urlConnection.getOutputStream();
- FileInputStream fileInputStream = new FileInputStream(localFile);
- IOUtils.copy(fileInputStream, urlOutputStream);
- // byte[] buffer = new byte[10240];
- // long count = 0;
- // int n = 0;
- // while (-1 != (n = fileInputStream.read(buffer))) {
- // urlOutputStream.write(buffer, 0, n);
- // count += n;
- // urlOutputStream.flush();
- // }
- fileInputStream.close();
- urlOutputStream.close();
- System.out.println(urlConnection.getResponseCode());
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }