问题描述
我有一个java方法,该方法以字符串形式返回网站的响应。现在,我想增加跟踪此请求进度的可能性。我知道我可以通过(contenLength / readBytes)* 100进行计算。但是我不确定如何正确检索此信息并在每次更改时更新进度。我当前的方法如下:
i got a java method which returns the response of the website in a string. Now i want to add the possibility to track the progress of this request. I know i can calculate it via (contenLength/readBytes) *100. But i am not sure how to retrieve this information properly and update the progress everytime it changes. My current method looks like this:
public String executePost(URL url) {
StringBuffer sb = new StringBuffer();
int readBytes = 0;
int contentLength = 0;
int progress = 0;
try {
String newString = url.toString().replace(" ", "%20");
URL newURL = new URL(newString);
URLConnection conn = newURL.openConnection();
conn.setDoOutput(true);
contentLength = conn.contentLength();
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
readBytes += line.getBytes("ISO-8859-2").length + 2;
progress = (readBytes/contentLength)*100;
System.out.println(progress);
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
推荐答案
您可以创建InputStream跟踪进度,例如
You can create an InputStream tracking the progress, e.g.
public class CountingInputStream extends FilterInputStream {
long count;
protected CountingInputStream(InputStream in)
{
super(in);
}
public long getCount()
{
return count;
}
@Override
public int read() throws IOException
{
final int read = super.read();
if(read>=0) count++;
return read;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
final int read = super.read(b, off, len);
if(read>0) count+=read;
return read;
}
@Override
public long skip(long n) throws IOException {
final long skipped = super.skip(n);
if(skipped>0) count+=skipped;
return skipped;
}
}
然后更改行
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
到
CountingInputStream counting = new CountingInputStream(conn.getInputStream());
BufferedReader rd = new BufferedReader(new InputStreamReader(counting));
然后您可以像以前一样继续进行操作,并通过 counting.getCount查询实际计数()
。
then you can proceed as before and query the acual count via counting.getCount()
.
请注意,在使用整数运算时,必须确保精度损失不会太大,因为进度总是较小等于或等于总数。因此,您应该使用 progressInPercent = progressInBytes * 100 / totalNumberOfBytes
。
Note that when you are using integer arithmetic you must ensure that the precision loss is not too big as the progress is always smaller than or equal to the total count. So you should use progressInPercent=progressInBytes*100/totalNumberOfBytes
.
请注意,在使用Swing时,类已经和提供类似的功能。
Note that when you are using Swing, there are already the classes ProgressMonitor
and ProgressMonitorInputStream
providing a similar functionality.
这篇关于在Java中获取HTTPRequest的进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!