如何知道Android HttpClient的进展?

时间:2014-10-13 11:30:56

标签: android httpwebrequest androidhttpclient

我正在使用以下功能从网络服务器下载一些html。然后想在webview中显示它。

private static final String request(String url) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;
    HttpGet get = new HttpGet(url);
    try {
        response = httpclient.execute(get);
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
        } else{
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        //TODO Handle problems..
    } catch (IOException e) {
        //TODO Handle problems..
    }
    return responseString;
}

我在AsynTask中使用该功能。这是包含AsyncTask代码的函数。

private void downloadInBackground(final String url, final WebView webview) {

    new AsyncTask<String, String, String>() {
        @Override
        protected String doInBackground(String... strings) {
            Log.d("asyncdebug", "sending!");
            String response = request(url);
            return response;
        }

        @Override
        protected void onPostExecute(String response) {
            Log.d("asyncdebug", "received!");
            webview.loadDataWithBaseURL("http://www.somedomainname.com/new/",response, "text/html", "UTF-8", null);
            super.onPostExecute(response);

        }


        @Override
        protected void onProgressUpdate(String... param) {
            Log.d("asyncdebug", "progressing... ");
        }


    }.execute("");
}

如何在此处获取下载过程的更新进度?

1 个答案:

答案 0 :(得分:0)

如果您不知道正在下载的数据大小,可以使用不确定的进度条。

例如,您可以将它放入AsyncTask onPreExecute:

        mProgressDialog = ProgressDialog.show(MyActivity.this, "", "Downloading...", true);
        mProgressDialog.setCancelable(false);

然后在你的onPostExecute:

        mProgressDialog.dismiss();

此处有更多信息:Android ProgressDialog