java - Is it possible to check progress of URLconnection.getInputStream()? -
i want check progress of downloading file urlconnection. possible or should use library? urlconnection function:
public static string sendpostrequest(string httpurl, string data) throws unsupportedencodingexception, malformedurlexception, ioexception { url url = new url(httpurl); urlconnection conn = url.openconnection(); //conn.addrequestproperty("content-type", "text/html; charset=iso-8859-2"); conn.setdooutput(true); outputstreamwriter wr = new outputstreamwriter(conn.getoutputstream()); wr.write(data); wr.flush(); bufferedreader rd = new bufferedreader(new inputstreamreader(conn.getinputstream(), "iso-8859-2")); string line, = ""; while ((line = rd.readline()) != null) { = + line; } wr.close(); rd.close(); return all; }
i understand whole file downloaded in line (or worng)?:
bufferedreader rd = new bufferedreader(new inputstreamreader(conn.getinputstream(), "iso-8859-2"));
so possible in code?
just check if http content-length
header present in response.
int contentlength = connection.getcontentlength(); if (contentlength != -1) { // (readbytes / contentlength) * 100 calculate percentage. } else { // you're lost. show "progress: unknown" }
update per update, you're wrapping inputstream
inside bufferedreader
, reading inside while
loop. can count bytes follows:
int readbytes = 0; while ((line = rd.readline()) != null) { readbytes += line.getbytes("iso-8859-2").length + 2; // crlf bytes!! // line. }
the + 2
cover crlf (carriage return , linefeed) bytes eaten bufferedreader#readline()
. more clean approach read inputstream#read(buffer)
don't need massage bytes forth , characters calculate read bytes.
Comments
Post a Comment