3

I created simple upload speed test, see code below:

try {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    byte [] array = new byte [1 * 1024 * 1024]; // 1 Mb data test
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    multipartEntity.addPart("", new ByteArrayBody(array, MIME.ENC_BINARY, ""));
    conn.addRequestProperty(multipartEntity.getContentType().getName(), multipartEntity.getContentType().getValue());

    conn.setReadTimeout(connTimeout);
    conn.setConnectTimeout(connTimeout);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");

    long start = System.currentTimeMillis();
    DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream());
    dataStream.write(array);

    String CRLF = "\r\n"; // Line separator required by multipart/form-data.
    String boundary = multipartEntity.getContentType().getValue().replaceAll(".*boundary=", "");
    dataStream.writeBytes("--" + boundary + CRLF);

    dataStream.flush();
    dataStream.close();

    int responseCode = conn.getResponseCode();    
    long end = System.currentTimeMillis();

    if (responseCode == HttpURLConnection.HTTP_OK) {
        long speed = Math.round(array.length/ (end-start));
        } else {
            // something went wrong
        }

Everything works perfect, but I have small problem. On fast networks like wifi it takes less than second to send 1 Mb of data. But on slower networks it takes maybe 10-30 seconds, depending on network and signal. So I realize, that it would be much better to not upload data with fixed length, but use something like time limit - so uploading data not more than for example 3 seconds.

Question is simple :) How to implement this - I mean sending data, computing time in same moment, and when the limit expires just stop sending, see how much I sent and compute speed?

qkx
  • 2,383
  • 5
  • 28
  • 50

2 Answers2

2

How about using something like a binary search, so you start with a small amount of data and keep doubling in size until your resulting time is long enough for a reasonable idea of the bandwidth.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • hm, I thought it would be best do something like this: while (notExpiredTimeLimit) { send to server (another 1000 bytes of my array) } Problem is, that I really do not know how to do this....As it looks that data are sending to server in line conn.getResponseCode() what makes impossible for me to do anything with it :) – qkx Nov 11 '13 at 10:02
1

the amount of bytes you send is not that important. even if you upload 50 KB when you divide that by the milliseconds the upload took (for fast connections that number will be relatively small) the division will result in a relatively big number. Conclusion: be safe and reduce the amount of bytes you send.

Clint Eastwood
  • 4,995
  • 3
  • 31
  • 27