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?