I implemented a WebRequest class for my basic GET and POST requests to URLConnections.
One of the features is submitting files - Now I'd like to calculate and display the progress of the uploading file - but I don't know how to do that:
for (KeyFilePair p : files) {
if (p.file != null && p.file.exists()) {
output.writeBytes("--" + boundary + "\n");
output.writeBytes("Content-Disposition: form-data; name=\""
+ p.key + "\"; filename=\"" + p.file.getName() + "\"\n");
output.writeBytes("Content-Type: " + p.mimetype
+ "; charset=UTF-8\n");
output.writeBytes("\n");
InputStream is = null;
try {
long max = p.file.length();
long cur = 0;
is = new FileInputStream(p.file);
int read = 0;
byte buff[] = new byte[1024];
while ((read = is.read(buff, 0, buff.length)) > 0) {
output.write(buff, 0, read);
output.flush();
cur += read;
if (monitor != null) {
monitor.updateProgress(cur, max);
}
}
} catch (Exception ex) {
throw ex;
} finally {
if (is != null) {
try {
is.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
output.writeBytes("\n--" + boundary + "--\n");
In this code you see the basic calculation of written bytes to the OutputStream output. But since the request isn't even sent to the server prior opening the InputStream of my connection (or reading the statuscode), this byte counting is completelly useless and only displays the progress of the request preparation.
So my question is: How can I monitor the current state of actually sent bytes to the server? I already checked the Java sources of getInputStream of the corresponding classes (HttpUrlConnection) to try to understand how and when there are actually bytes written to the server... but with no conclusion.
Is there a way to do that without writing my own implementation of the http protocoll?
Thanks
Best regards matt