`

HttpURLConnection 上传大文件 内存溢出 out of memery

 
阅读更多

项目中遇到问题总结一下:

在使用HttpURLConnection 上传大文件时,出现内存溢出的错误,这让我产生了错觉,输入和输出流咋会暂用内存,不就是一个数据传送的管道么,都没有把数据读取到内存中,为撒会报错。。。然后就纠结了。。。

不过实在与原来的经验相违背,然后写了一个示例直接从file中读出然后写入到输出流中,发现并没有问题

这下确认了问题出在HttpURLConnection,查看API发现,HTTP会有缓冲机制,缓存把JVM撑挂了导致内存溢出了。。。。

通过设置以下方法即可解决问题

setFixedLengthStreamingMode

public void setFixedLengthStreamingMode(int contentLength)
此方法用于在预先已知内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。

如果应用程序尝试写入的数据多于指示的内容长度,或者应用程序在写入指示的内容长度前关闭了 OutputStream,将抛出异常。

启用输出流时,不能自动处理验证和重定向。如果需要验证和重定向,则在读取响应时将抛出 HttpRetryException。可以查询此异常以获取错误的详细信息。

该方法必须在连接 URLConnection 前调用。

 

  1. private void uploadFile()  
  2.     {  
  3.         String urlResouce = null;  
  4. //      urlResouce = "http://localhost:8080/application_interface_manager/platform/wangpan/444.png";  
  5.         urlResouce = "http://localhost:8080/application_interface_manager/platform/wangpan/myeclipse111.exe";  
  6.     try{  
  7. //      File localFile = new File("C:\\Users\\maomao\\Documents\\111.png");  
  8.         File localFile = new File("Z:\\tools\\myeclipse-8.5.0-win32.exe");  
  9.     //创建客户端签名  
  10.     String clientToken = new CreateSignTokenImpl().getToken("caizhonghu",secretKey);  
  11.     HttpURLConnection urlConnection =  
  12.     (HttpURLConnection) (new URL(urlResouce)).openConnection();  
  13.     urlConnection.setChunkedStreamingMode(0);  
  14.     urlConnection.setRequestProperty("Charset""UTF-8");  
  15.     urlConnection.setRequestProperty("Token""jingdong "+accessKey+":"+clientToken);  
  16.     urlConnection.setDoInput(true);  
  17.     urlConnection.setDoOutput(true);  
  18.     urlConnection.setRequestMethod("PUT");  
  19.     OutputStream urlOutputStream = urlConnection.getOutputStream();  
  20.     FileInputStream fileInputStream = new FileInputStream(localFile);  
  21.     IOUtils.copy(fileInputStream, urlOutputStream);  
  22.       
  23. //   byte[] buffer = new byte[10240];  
  24. //     long count = 0;  
  25. //     int n = 0;  
  26. //     while (-1 != (n = fileInputStream.read(buffer))) {  
  27. //       urlOutputStream.write(buffer, 0, n);  
  28. //         count += n;  
  29. //         urlOutputStream.flush();  
  30. //     }  
  31.     fileInputStream.close();  
  32.     urlOutputStream.close();  
  33.     System.out.println(urlConnection.getResponseCode());  
  34.     }  
  35.     catch(Exception e)  
  36.     {  
  37.         e.printStackTrace();  
  38.     }  
  39.     } 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics