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

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

在使用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();
	}
	}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值