如何从一个BufferedReader进度百分比? [英] How to get percentage progress from a BufferedReader?

查看:571
本文介绍了如何从一个BufferedReader进度百分比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  @覆盖
    保护StringBuilder的doInBackground(字符串... URL){
        尝试{
            HttpClient的客户端=新DefaultHttpClient();
            HTTPGET请求=新HTTPGET(URL [0]);
            HTT presponse响应= client.execute(请求);
            RD的BufferedReader =新的BufferedReader(新的InputStreamReader(
                    。response.getEntity()的getContent()));
            长含量= response.getEntity()getContentLength()。
//不需要串线
            串线=;
            StringBuilder的htmlBuilder =新的StringBuilder();
            长读取动作= 0;
            而((行= rd.readLine())!= NULL){
                htmlBuilder.append(线);
                读取动作=读取动作+ line.getBytes()长度+ 2。
                publishProgress(新的整数[] {(INT)(((双)读取动作/(双)的含量)* 100)});
            }
            返回htmlBuilder;
        }赶上(IOException异常五){
            返回null;
        }    }

长内容'返回一个-1。这意味着内容是比长类的最大值大。

要尝试并使其返回别的东西,我试图扩大DefaultHttpClient =>

 公共类ImprovedHttpClient扩展DefaultHttpClient实现的HttpClient {
    @覆盖
公众最终的Htt presponse执行(HttpUriRequest要求)
        抛出IOException异常,ClientProtocolException {
    // TODO自动生成方法存根
    返回super.execute(请求);
}

}

以上方法最终让我无法扩展它,并使用多态...我停留在如何获得的百分比进度,我不希望使用另一个库。

为什么我要实现的HttpClient?据Apache文档,DefaultHttpClient已经实现了HttpClient的;它没有任何意义,我要实现它。不过,我可以看到日食将$ P $从寻找它,因为最后的方法不能扩展pvent我。

在最后,我如何获得内容从DefaultHttpClient的总字节数没有它返回-1?

编辑
这是从印刷

 的System.out.println(Arrays.toString(response.getAllHeaders()));

#1成功给我回使用这个网址的进度百分比: <$c$c>(\"http://stackoverflow.com/questions/20306245/how-to-get-percentage-progress-from-a-bufferedreader#20306306\");

  [缓存控制:公众,最大年龄= 33,内容类型:text / html的;字符集= UTF-8,截止日期:星期六,2013年11月30日22时37分十四秒GMT,最后修改:周六,二○一三年十一月三十日22时36分14秒格林尼治标准​​时间,各不相同:*,X帧选项:SAMEORIGIN,日期:星期六,2013年11月30日22时36分41秒格林尼治标准​​时间,内容长度:51468,途经:HTTP / 1.1 127.0.0.1:2020(巴西/ 2.0),服务器:巴西/ 2.0连接:保持活动]

谷歌返回-1:
     https://www.google.com/

  [日期:星期六,2013年11月30日22时41分四十四秒GMT,到期日:-1,缓存控制:私人,最大年龄= 0,内容类型:text / HTML;字符集= ISO-8859-1,设置Cookie:preF = ID = 4c028dc2b639abc2:FF = 0:TM = 1385851304:LM = 1385851304:S =我们-TWKR-LtJcomHN;到期=周一,11月30日 -  2015年二十二时41分44秒格林尼治标准​​时间;路径= /;域= .google.com,设置Cookie: NID=67=mId7x6boTt6BYcAWipXzM4Fjt_WGl7KQPgcHdPkA9yiOgHf8pTWl5k38AfFnA68NjL34rDRYsveh-QdLKcyoAzDZRigGe_5ydrwiELRSkW24Q0J7NdtErEnT93WXMjgM;到期=孙,01军,2014年二十二时41分44秒格林尼治标准​​时间;路径= /;域= .google.com;仅Http,P3P:CP =这不是一个P3P策略请参见http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657更多信息!,服务器: GWS,X-XSS-保护:1;模式=块,X帧选项:SAMEORIGIN,复用协议:443:QUIC,传输编码:分块]


解决方案

有一些情况,一个HTTP客户端无法知道你所得到的东西的尺寸。 HTTP头具有申报内容长度的地方,但是这不是必需的。在服务器不指定的内容长度的情况下,HTTPEntity返回-1的长度。

在这种情况下,没有办法准确地报告下载进度。你可以做一个猜测的内容长度。或者,如果有下载后显著的处理,你可以下载整个事情,然后报告的处理进展情况。

请检查服务器发送了正在测试的情况下,内容长度。

@Override
    protected StringBuilder doInBackground(String... url) {
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url[0]);
            HttpResponse response = client.execute(request);
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            long content = response.getEntity().getContentLength();
//Do not need 'String line'
            String line = "";
            StringBuilder htmlBuilder = new StringBuilder();
            long bytesRead = 0;
            while ((line = rd.readLine()) != null) {
                htmlBuilder.append(line);
                bytesRead = bytesRead + line.getBytes().length + 2;
                publishProgress(new Integer[]{(int) (((double) bytesRead / (double) content) * 100)});
            }
            return htmlBuilder;
        } catch (IOException e) {
            return null;
        }

    }

'long content' is returning a -1. This means that the content is larger than the max value of the long class.

To try and have it return something else I tried to extend DefaultHttpClient=>

public class ImprovedHttpClient extends DefaultHttpClient implements HttpClient {
    @Override
public final HttpResponse execute(HttpUriRequest request)
        throws IOException, ClientProtocolException {
    // TODO Auto-generated method stub
    return super.execute(request);
}

}

The above method is final so I cannot extend it and use polymorphism...I am stuck on how to get the percent progress and I do not want to use another library.

Why do I have to implement HttpClient? According to apache documentation, DefaultHttpClient already implements HttpClient; it makes no sense that I have to implement it. However, I can see how eclipse would prevent me from finding it because final methods cannot be extended.

In conclusion, How do I get the total bytes of content from the DefaultHttpClient without it returning -1?

EDIT This is printed from

System.out.println(Arrays.toString(response.getAllHeaders()));

Stackoverflow successfully gives me back the percentage progress using this url: ("http://stackoverflow.com/questions/20306245/how-to-get-percentage-progress-from-a-bufferedreader#20306306");

[Cache-Control: public, max-age=33, Content-Type: text/html; charset=utf-8, Expires: Sat, 30 Nov 2013 22:37:14 GMT, Last-Modified: Sat, 30 Nov 2013 22:36:14 GMT, Vary: *, X-Frame-Options: SAMEORIGIN, Date: Sat, 30 Nov 2013 22:36:41 GMT, Content-Length: 51468, Via: HTTP/1.1 127.0.0.1:2020 (Brazil/2.0), Server: Brazil/2.0, Connection: Keep-Alive]

Google Returns -1: https://www.google.com/

[Date: Sat, 30 Nov 2013 22:41:44 GMT, Expires: -1, Cache-Control: private, max-age=0, Content-Type: text/html; charset=ISO-8859-1, Set-Cookie: PREF=ID=4c028dc2b639abc2:FF=0:TM=1385851304:LM=1385851304:S=we-TWKR-LtJcomHN; expires=Mon, 30-Nov-2015 22:41:44 GMT; path=/; domain=.google.com, Set-Cookie: NID=67=mId7x6boTt6BYcAWipXzM4Fjt_WGl7KQPgcHdPkA9yiOgHf8pTWl5k38AfFnA68NjL34rDRYsveh-QdLKcyoAzDZRigGe_5ydrwiELRSkW24Q0J7NdtErEnT93WXMjgM; expires=Sun, 01-Jun-2014 22:41:44 GMT; path=/; domain=.google.com; HttpOnly, P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info.", Server: gws, X-XSS-Protection: 1; mode=block, X-Frame-Options: SAMEORIGIN, Alternate-Protocol: 443:quic, Transfer-Encoding: chunked]

解决方案

There are some situations where an HTTP client can not know the size of the thing you are getting. The HTTP header has a place to declare the content length, but that is not required. In the situation where the server does not specify the content length, the HTTPEntity returns a -1 for length.

In this situation there is no way to report download progress accurately. You could make a "guess" at the content length. Or if there is significant processing after download, you could download the entire thing, and then report progress on the processing.

Check to see if the server is sending the content length for the case you are testing.

这篇关于如何从一个BufferedReader进度百分比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆