0

I am trying to upload some bytes to the server for 15 seconds.I have written the following code to write the bytes to output stream :

        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);
            }

But the progress for the above upload is running very fast and it shows large amount of bytes uploaded within seconds.Which is not according to my 2g mobile network connection. For example it shows : uploadedBytes =9850880 and with time difference(timeDiff) = 3 sec.

if i run the same code for 15 seconds it terminates the whole application. Please help me to find where i am goind wrong. thanks ...waiting for reply

4

2 に答える 2

0

チャンクまたはストリーミング転送モードを設定しない限り、HttpURLConnectionすべての出力を送信する前にバッファリングするため、Content-Length を取得できます。したがって、転送ではなく、バッファリングの進行状況が表示されます。チャンク転送モードを設定すると、違いがわかります。

コピー ループが間違っています。次のようになります。

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

あなたのコードはおそらくこの特定のケースで機能しますが、それはすべてのケースで正しく動作しない理由ではありません。

于 2013-06-05T23:46:46.047 に答える