java url 连接,等待通过输出流发送数据

标签 java url upload connection outputstream

我正在编写一个java类来测试上传到服务器的速度连接。我想检查5秒内可以发送多少数据。

我编写了一个类,它创建 URL、创建连接并通过 outPutStream 发送数据。有一个循环,我将数据写入流 5 秒。但是我无法看到数据何时发送(我将数据写入输出流,但数据尚未发送)。如何才能等到数据真正发送到服务器? 这是我的代码(不起作用):

URL u = new URL(url)
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setUseCaches(false);
uc.setDefaultUseCaches(false);
uc.setRequestMethod("POST");
uc.setRequestProperty("Content-Type", "application/octet-stream");
uc.connect();
st.start();

// Send the request
OutputStream os = uc.getOutputStream();
//This while is incorrect cause it does not wait for data beeing sent
while (st.getElapsedTime() < miliSeconds) {
    os.write(buffer);
    os.flush();
    st.addSize(buffer.length);

}
os.close();

谢谢

最佳答案

默认情况下,整个输出流在发送之前缓冲在内存中。您需要启用分块流模式或固定长度流模式,以便输出流直接写入而无需缓冲。

在这里添加

HttpURLConnection uc = (HttpURLConnection) u.openConnection();
uc.setChunkedStreamingMode(8192); // <-- enable chunked streaming mode before connecting to server.

关于java url 连接,等待通过输出流发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4624680/

相关文章:

java - JAX-RS 与 RESTeasy : automatic scanning of resources?

java - 如何在您自己的 NamingStrategy 实现中处理 @JoinColumn?

java - ExecutorService.shutDown() 和 ExecutorService.shutDownNow() 之间的中间地带

url - 使用 wget 从正确的 Apache Mirror 下载文件

php - 使用 php 和 mysql 上传多个文件?

php使用ajax上传图片并在上传后显示图片

c# - .NET MVC3 图片上传相关错误 : conversion from type 'System.Web.HttpPostedFileWrapper' to type 'Project.Domain.Entities.Image'

java - 意外的类型删除

r - 如何使用wav文件的URL在R中加载wav文件?

python - 从 URL python 中删除 HTTP 和 WWW