Reputation: 2563
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?
Upvotes: 3
Views: 2320
Reputation: 5698
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.
Upvotes: 1
Reputation: 207345
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.
Upvotes: 2