【问题标题】:uploading bytes to server via outputstream通过输出流将字节上传到服务器
【发布时间】:2013-06-05 13:19:49
【问题描述】:

我正在尝试将一些字节上传到服务器 15 秒。我编写了以下代码将字节写入输出流:

        long uploadedBytes=0;
        ByteArrayInputStream byteArrayInputStream=null;
        OutputStream outputStream=null;
        try {
            byte[] randomData=generateBinData(5*1024);
            byte[] bytes = new byte[(int) 1024 * 5];
            URL url = new URL(urls[0]);
            HttpURLConnection connection = 
                    (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            outputStream = connection.getOutputStream();

            byteArrayInputStream = new ByteArrayInputStream(randomData);
            long startTime=System.currentTimeMillis();
            while(byteArrayInputStream.read(bytes) > 0 
                    && timeDiff < 15000) {
                outputStream.write(bytes, 0, bytes.length);
                uploadedBytes += bytes.length;
                byteArrayInputStream = new ByteArrayInputStream(randomData);
                timeDiff = System.currentTimeMillis() - startTime;
                int progress=(int)(timeDiff *100 / 15000);
                publishProgress(progress);
            }

但是上面的上传进度非常快,显示几秒钟内上传了大量的字节。这不是根据我的 2g 移动网络连接。 例如它显示: uploadBytes =9850880 和时间差(timeDiff)= 3 秒。

如果我运行相同的代码 15 秒,它会终止整个应用程序。 请帮我找出我哪里出错了。 谢谢...等待回复

【问题讨论】:

    标签: java android upload network-programming


    【解决方案1】:

    除非您设置分块或流传输模式,HttpURLConnection 会在发送任何输出之前缓冲所有输出,因此它可以获得 Content-Length。因此,您看到的是缓冲的进度,而不是传输的进度。设置分块传输模式,你会看到不同。

    你的复制循环是错误的。应该是这样的:

    while ((count = in.read(buffer)) > 0)
    {
        out.write(buffer, 0, count);
    }
    

    您的代码可能会在这种特定情况下工作,但这并不是不适合所有情况的理由。

    【讨论】:

      【解决方案2】:

      检查您的随机字节长度。我认为 generateBinData() 方法没有生成 5Kb 的数据。

      确定上传的字节数很大。比如说,如果写入输出流需要 10 毫秒来写入 5Kb(5*1024) 的数据,那么在 3 秒内你应该只能写入 153600 字节。

      应用程序终止的原因 - 检查是否有任何读取操作引发异常。

      【讨论】:

        猜你喜欢
        • 2022-11-22
        • 1970-01-01
        • 2014-07-11
        • 2013-08-23
        • 1970-01-01
        • 1970-01-01
        • 2011-06-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多