当前位置: 首页 > news >正文

HttpURLConnection OOM问题记录

使用HttpURLConnection 上传大文件,会出现内存溢出问题:

观察HttpURLConnection 源码:

@Overridepublic synchronized OutputStream getOutputStream() throws IOException {connecting = true;SocketPermission p = URLtoSocketPermission(this.url);if (p != null) {try {return AccessController.doPrivilegedWithCombiner(new PrivilegedExceptionAction<>() {public OutputStream run() throws IOException {return getOutputStream0();}}, null, p            );} catch (PrivilegedActionException e) {throw (IOException) e.getException();}} else {return getOutputStream0();}
}

private synchronized OutputStream getOutputStream0() throws IOException {try {if (!doOutput) {throw new ProtocolException("cannot write to a URLConnection"                           + " if doOutput=false - call setDoOutput(true)");}if (method.equals("GET")) {method = "POST"; // Backward compatibility        }if ("TRACE".equals(method) && "http".equals(url.getProtocol())) {throw new ProtocolException("HTTP method TRACE" +" doesn't support output");}// if there's already an input stream open, throw an exception        if (inputStream != null) {throw new ProtocolException("Cannot write output after reading input.");}if (!checkReuseConnection())connect();boolean expectContinue = false;String expects = requests.findValue("Expect");if ("100-Continue".equalsIgnoreCase(expects) && streaming()) {http.setIgnoreContinue(false);expectContinue = true;}if (streaming() && strOutputStream == null) {writeRequests();}if (expectContinue) {expect100Continue();}ps = (PrintStream)http.getOutputStream();if (streaming()) {if (strOutputStream == null) {if (chunkLength != -1) { /* chunked */                     strOutputStream = new StreamingOutputStream(new ChunkedOutputStream(ps, chunkLength), -1L);} else { /* must be fixed content length */                    long length = 0L;if (fixedContentLengthLong != -1) {length = fixedContentLengthLong;} else if (fixedContentLength != -1) {length = fixedContentLength;}strOutputStream = new StreamingOutputStream(ps, length);}}return strOutputStream;} else {if (poster == null) {poster = new PosterOutputStream();}return poster;}} catch (RuntimeException e) {disconnectInternal();throw e;} catch (ProtocolException e) {// Save the response code which may have been set while enforcing        // the 100-continue. disconnectInternal() forces it to -1        int i = responseCode;disconnectInternal();responseCode = i;throw e;} catch (IOException e) {disconnectInternal();throw e;}
}

public boolean streaming () {return (fixedContentLength != -1) || (fixedContentLengthLong != -1) ||(chunkLength != -1);
}

如上, 默认设置情况下streaming ()  为false。

package sun.net.www.http
public class PosterOutputStream extends ByteArrayOutputStream {
}

PosterOutputStream  默认为 ByteArrayOutputStream  子类

解决办法:

目标服务支持情况下,可以不使用HttpURLConnection的ByteArrayOutputStream缓存机制,直接将流提交到服务器上。如下函数设置:

httpConnection.setChunkedStreamingMode(0); // 或者设置自定义大小,0默认大小

    public void setChunkedStreamingMode (int chunklen) {if (connected) {throw new IllegalStateException ("Can't set streaming mode: already connected");}if (fixedContentLength != -1 || fixedContentLengthLong != -1) {throw new IllegalStateException ("Fixed length streaming mode set");}chunkLength = chunklen <=0? DEFAULT_CHUNK_SIZE : chunklen;}

遗憾的是,我上传的服务不支持这种模式。因此采用固定大小。

HttpURLConnection con = (HttpURLConnection)new URL("url").openConnection();
con.setFixedLengthStreamingMode(输出流的固定长度);
  /*** This method is used to enable streaming of a HTTP request body* without internal buffering, when the content length is known in* advance.* <p>* An exception will be thrown if the application* attempts to write more data than the indicated* content-length, or if the application closes the OutputStream* before writing the indicated amount.* <p>* When output streaming is enabled, authentication* and redirection cannot be handled automatically.* A HttpRetryException will be thrown when reading* the response if authentication or redirection are required.* This exception can be queried for the details of the error.* <p>* This method must be called before the URLConnection is connected.* <p>* <B>NOTE:</B> {@link #setFixedLengthStreamingMode(long)} is recommended* instead of this method as it allows larger content lengths to be set.** @param   contentLength The number of bytes which will be written*          to the OutputStream.** @throws  IllegalStateException if URLConnection is already connected*          or if a different streaming mode is already enabled.** @throws  IllegalArgumentException if a content length less than*          zero is specified.** @see     #setChunkedStreamingMode(int)* @since 1.5*/public void setFixedLengthStreamingMode (int contentLength) {if (connected) {throw new IllegalStateException ("Already connected");}if (chunkLength != -1) {throw new IllegalStateException ("Chunked encoding streaming mode set");}if (contentLength < 0) {throw new IllegalArgumentException ("invalid content length");}fixedContentLength = contentLength;}

我是上传文件场景: 使用文件的大小作为长度

FileInputStream fileInputStream = new FileInputStream(uploadFileName);
long totalLength= fileInputStream.getChannel().size();
var boundary = "someboundary";
var temUploadUrl = "url path";
//
var url = new URL(temUploadUrl);
var connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", MediaType.MULTIPART_FORM_DATA_VALUE + "; boundary=" + boundary);connection.setDoOutput(true);
// 设置 Content-Length
connection.setRequestProperty("Content-Length", String.valueOf(totalLength)); 
connection.setFixedLengthStreamingMode(totalLength);

相关文章:

HttpURLConnection OOM问题记录

使用HttpURLConnection 上传大文件&#xff0c;会出现内存溢出问题&#xff1a; 观察HttpURLConnection 源码&#xff1a; Overridepublic synchronized OutputStream getOutputStream() throws IOException {connecting true;SocketPermission p URLtoSocketPermission(th…...

WT588F02B单片机语音芯片在磁疗仪中的应用介绍

随着健康意识的普及和科技的发展&#xff0c;磁疗仪作为一种常见的理疗设备&#xff0c;受到了广大用户的关注。为了提升用户体验和操作便捷性&#xff0c;唯创知音WT588F02B单片机语音芯片被成功应用于磁疗仪中。这一结合将为磁疗仪带来智能化的语音交互功能&#xff0c;为用户…...

深度学习——第5章 神经网络基础知识

第5章 神经网络基础知识 目录 5.1 由逻辑回归出发 5.2 损失函数 5.3 梯度下降 5.4 计算图 5.5总结 在第1课《深度学习概述》中&#xff0c;我们介绍了神经网络的基本结构&#xff0c;了解了神经网络的基本单元组成是神经元。如何构建神经网络&#xff0c;如何训练、优化神…...

微信网页授权步骤说明

总览 引导用户进入授权页面同意授权&#xff0c;获取code通过code换取网页授权access_token&#xff08;与基础支持中的access_token不同&#xff09;如果需要&#xff0c;开发者可以刷新网页授权access_token&#xff0c;避免过期&#xff08;一般不需要&#xff09;通过网页…...

linux bash shell变量操作符 —— 筑梦之路

1. 变量子串 ${var} 返回变量var的内容&#xff0c;单独使用时有没有{}一样&#xff0c;混合多个变量和常量时&#xff0c;用{}界定变量名 ${#var} 返回变量var内容的长度 ${var:offset} 从变量var中的偏移量offset开始截取到字符串结尾的子字符串&#xff0c;offset从0开始 ${…...

2.61【Python生成器与迭代器】

Python迭代器与生成器 迭代器 什么是迭代器 首先迭代是指python中访问元素的一种方式&#xff0c;迭代器是一个可以记住遍历位置的对象&#xff0c;因此不会像列表那样一次性全部生成&#xff0c;而是可以等到用的时候才生成&#xff0c;因此节省了大量的内存资源 可迭代对…...

devecho stuido npm 失败

使用华为推荐的设置npm 代理方式仍然无效。还是得使用npm 命令去设置代理。地址参考&#xff1a; npm设置和取消代理的方法_npm查看代理-CSDN博客 最后使用自己的代理加载成功&#xff0c;使用华为推荐的代理不成功&#xff0c;不清楚什么原因。 华为推荐的环境配置如下&…...

postgreSql逻辑复制常用语句汇总和说明

简单说明 postgreSql逻辑复制的原理这里不再赘述&#xff0c;度娘一下即可。这里只是对常用的语句做一些汇总和说明&#xff0c;以便日后查找时方便。 逻辑复制的概念 逻辑复制整体上采用的是一个发布订阅的模型&#xff0c;订阅者可以订阅一个或者多个发布者&#xff0c; 发…...

设置Ubuntu或树莓派系统,允许root用户ssh方式连接

Ubuntu 或 Raspbian 系统默认不允许root 用户以ssh方式连接。连接会报如下错误&#xff1a; Permission denied&#xff0c; please try again. 解决步骤&#xff1a; &#xff08;如果是树莓派系统&#xff1a;烧录到内存卡后&#xff0c;拔掉内存卡再重新插到PC机上&#x…...

Ubuntu安装向日葵【远程控制】

文章目录 引言下载向日葵安装向日葵运行向日葵卸载向日葵参考资料 引言 向日葵是一款非常好用的远程控制软件。这一篇博文介绍了如何在 Ubuntu Linux系统 中安装贝瑞向日葵。&#x1f3c3;&#x1f4a5;&#x1f4a5;&#x1f4a5;❗️ 下载向日葵 向日葵官网: https://sunl…...

jquery 实现倒计时60秒

jquery 实现倒计时60秒 <!DOCTYPE html> <html><head><meta http-equiv"content-type" content"text/html; charsetUTF-8"><meta content"widthdevice-width,initial-scale1.0,maximum-scale1.0,user-scalableno" i…...

单例模式:饿汉模式、懒汉模式

目录 一、什么是单例模式 二、饿汉模式 三、懒汉模式 一、什么是单例模式 单例模式是Java中的设计模式之一&#xff0c;能够保证某个类在程序中只存在唯一一份实例&#xff0c;而不会创建出多个实例 单例模式有很多实现方式&#xff0c;最常见的是饿汉和懒汉两种模式 二、…...

提升方法AdaBoost

通过改变训练样本的权重学习多个分类器&#xff0c;并将这些线性分类器进行线性组合&#xff0c;提高分类性能。 AdaBoost 提高前一轮被分类错误的权值&#xff0c;降低前一轮被分类正确的权值&#xff1b;加大分类误差错误率小的弱分类器权重。 算法&#xff1a; 输入&…...

Python自动化测试系列[v1.0.0][多种数据驱动实现附源码]

前情提要 请确保已经熟练掌握元素定位的常用方法及基本支持&#xff0c;请参考Python自动化测试系列[v1.0.0][元素定位] 数据驱动测试是自动化测试中一种重要的设计模式&#xff0c;这种设计模式可以将测试数据和测试代码分开&#xff0c;实现数据与代码解耦&#xff0c;与此同…...

【论文笔记】Gemini: A Family of Highly Capable Multimodal Models——细看Gemini

Gemini 【一句话总结&#xff0c;对标GPT4&#xff0c;模型还是transformer的docoder部分&#xff0c;提出三个不同版本的Gemini模型&#xff0c;Ultra的最牛逼&#xff0c;Nano的可以用在手机上。】 谷歌提出了一个新系列多模态模型——Gemini家族模型&#xff0c;包括Ultra…...

iOS加密CoreML模型

生成模型加密密钥 必须在Xcode的Preferences的Accounts页面登录Apple ID&#xff0c;才能在Xcode中生成模型加密密钥。 在Xcode中打开模型&#xff0c;单击Utilities选项卡&#xff0c;然后单击“Create Encryption Key”按钮。 从下拉菜单中选择当前App的Personal Team&…...

Springboot自定义start首发预告

Springboot自定义start首发预告 基于Springboot的自定义start , 减少项目建设重复工作, 如 依赖 , 出入参包装 , 日志打印 , mybatis基本配置等等等. 优点 模块化 可插拔 易于维护和升级 定制化 社区支持(后期支持) 发布时间 预告: 2023-12-10 预计发布: 2024-1-1 , 元旦首…...

[GWCTF 2019]我有一个数据库1

提示 信息收集phpmyadmin的版本漏洞 这里看起来不像是加密应该是编码错误 这里访问robots.txt 直接把phpinfo.php放出来了 这里能看到它所有的信息 这里并没有能找到可控点 用dirsearch扫了一遍 ####注意扫描buuctf的题需要控制扫描速度&#xff0c;每一秒只能扫10个多一个都…...

【LeetCode每日一题】1904. 你完成的完整对局数

给你两个字符串 startTime 和 finishTime &#xff0c;均符合 "HH:MM" 格式&#xff0c;分别表示你 进入 和 退出 游戏的确切时间&#xff0c;请计算在整个游戏会话期间&#xff0c;你完成的 完整对局的对局数 。 如果 finishTime 早于 startTime &#xff0c;这表示…...

+0和不+0的性能差异

前几日&#xff0c;有群友转发了某位技术大佬的weibo。并在群里询问如下两个函数哪个执行的速度比较快&#xff08;weibo内容&#xff09;。 func g(n int, ch chan<- int) {r : 0for i : 0; i < n; i {r i}ch <- r 0 }func f(n int, ch chan<- int) {r : 0for …...

iOS 26 携众系统重磅更新,但“苹果智能”仍与国行无缘

美国西海岸的夏天&#xff0c;再次被苹果点燃。一年一度的全球开发者大会 WWDC25 如期而至&#xff0c;这不仅是开发者的盛宴&#xff0c;更是全球数亿苹果用户翘首以盼的科技春晚。今年&#xff0c;苹果依旧为我们带来了全家桶式的系统更新&#xff0c;包括 iOS 26、iPadOS 26…...

【人工智能】神经网络的优化器optimizer(二):Adagrad自适应学习率优化器

一.自适应梯度算法Adagrad概述 Adagrad&#xff08;Adaptive Gradient Algorithm&#xff09;是一种自适应学习率的优化算法&#xff0c;由Duchi等人在2011年提出。其核心思想是针对不同参数自动调整学习率&#xff0c;适合处理稀疏数据和不同参数梯度差异较大的场景。Adagrad通…...

Java如何权衡是使用无序的数组还是有序的数组

在 Java 中,选择有序数组还是无序数组取决于具体场景的性能需求与操作特点。以下是关键权衡因素及决策指南: ⚖️ 核心权衡维度 维度有序数组无序数组查询性能二分查找 O(log n) ✅线性扫描 O(n) ❌插入/删除需移位维护顺序 O(n) ❌直接操作尾部 O(1) ✅内存开销与无序数组相…...

dedecms 织梦自定义表单留言增加ajax验证码功能

增加ajax功能模块&#xff0c;用户不点击提交按钮&#xff0c;只要输入框失去焦点&#xff0c;就会提前提示验证码是否正确。 一&#xff0c;模板上增加验证码 <input name"vdcode"id"vdcode" placeholder"请输入验证码" type"text&quo…...

[ICLR 2022]How Much Can CLIP Benefit Vision-and-Language Tasks?

论文网址&#xff1a;pdf 英文是纯手打的&#xff01;论文原文的summarizing and paraphrasing。可能会出现难以避免的拼写错误和语法错误&#xff0c;若有发现欢迎评论指正&#xff01;文章偏向于笔记&#xff0c;谨慎食用 目录 1. 心得 2. 论文逐段精读 2.1. Abstract 2…...

Android15默认授权浮窗权限

我们经常有那种需求&#xff0c;客户需要定制的apk集成在ROM中&#xff0c;并且默认授予其【显示在其他应用的上层】权限&#xff0c;也就是我们常说的浮窗权限&#xff0c;那么我们就可以通过以下方法在wms、ams等系统服务的systemReady()方法中调用即可实现预置应用默认授权浮…...

OPenCV CUDA模块图像处理-----对图像执行 均值漂移滤波(Mean Shift Filtering)函数meanShiftFiltering()

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 在 GPU 上对图像执行 均值漂移滤波&#xff08;Mean Shift Filtering&#xff09;&#xff0c;用于图像分割或平滑处理。 该函数将输入图像中的…...

Typeerror: cannot read properties of undefined (reading ‘XXX‘)

最近需要在离线机器上运行软件&#xff0c;所以得把软件用docker打包起来&#xff0c;大部分功能都没问题&#xff0c;出了一个奇怪的事情。同样的代码&#xff0c;在本机上用vscode可以运行起来&#xff0c;但是打包之后在docker里出现了问题。使用的是dialog组件&#xff0c;…...

免费数学几何作图web平台

光锐软件免费数学工具&#xff0c;maths,数学制图&#xff0c;数学作图&#xff0c;几何作图&#xff0c;几何&#xff0c;AR开发,AR教育,增强现实,软件公司,XR,MR,VR,虚拟仿真,虚拟现实,混合现实,教育科技产品,职业模拟培训,高保真VR场景,结构互动课件,元宇宙http://xaglare.c…...

uniapp 开发ios, xcode 提交app store connect 和 testflight内测

uniapp 中配置 配置manifest 文档&#xff1a;manifest.json 应用配置 | uni-app官网 hbuilderx中本地打包 下载IOS最新SDK 开发环境 | uni小程序SDK hbulderx 版本号&#xff1a;4.66 对应的sdk版本 4.66 两者必须一致 本地打包的资源导入到SDK 导入资源 | uni小程序SDK …...