Android AsyncTask异步处理抓取网页

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

Android AsyncTask异步处理抓取网页

/**
 *
 * @author yanggang
 * @see http://blog.csdn.net/sunboy_2050
 */
public class MainActivity extends Activity {
    private EditText metURL;
    private TextView mtvPage;
    private Button mbtnConn;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        metURL = (EditText)findViewById(R.id.etURL);        // 输入网址
        mbtnConn = (Button)findViewById(R.id.btnConn);      // 连接网站
        mtvPage = (TextView)findViewById(R.id.tvPage);      // 显示网页
         
        mbtnConn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connURL();
            }
        });
    }
 
    private void connURL(){
        URLTask urlTask = new URLTask(this);    // 实例化抽象AsyncTask
        urlTask.execute(metURL.getText().toString().trim());    // 调用AsyncTask,传入url参数
    }
     
    /** 继承AsyncTask的子类,下载url网页内容 */
    class URLTask extends AsyncTask<String, Integer, String> {
        ProgressDialog proDialog;
         
        public URLTask(Context context) {
            proDialog = new ProgressDialog(context, 0);
            proDialog.setButton("cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            proDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    finish();
                }
            });
            proDialog.setCancelable(true);
            proDialog.setMax(100);
            proDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            proDialog.show();
        }
 
        @Override
        protected void onPreExecute(){
            mtvPage.setText(R.string.hello_world);      // 可以与UI控件交互
        }
         
        @Override
        protected String doInBackground(String... params) {     // 在后台,下载url网页内容
            try {
                HttpGet get = new HttpGet(params[0]);           // url
                HttpResponse response = new DefaultHttpClient().execute(get);
                 
                if(response.getStatusLine().getStatusCode() == 200) {       // 判断网络连接是否成功
//                  String result = EntityUtils.toString(response.getEntity(), "gb2312");   // 获取网页内容
//                  return result;
                     
                    HttpEntity entity = response.getEntity();
                    long len = entity.getContentLength();       // 获取url网页内容总大小
                    InputStream is = entity.getContent();
                     
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int ch = -1;
                    int count = 0;      // 统计已下载的url网页内容大小
                    while(is != null && (ch = is.read(buffer)) != -1 ) {
                        bos.write(buffer, 0, ch);
                        count += ch;
                        if(len > 0) {
                            float ratio = count/(float)len * 100;   // 计算下载url网页内容百分比
                            publishProgress((int)ratio);    // android.os.AsyncTask.publishProgress(Integer... values)
                        }
                        Thread.sleep(100);
                    }
                    String result = new String(bos.toString("gb2312"));
                    return result;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
             
            return null;
        }
         
        @Override
        protected void onProgressUpdate(Integer... values) {    // 可以与UI控件交互
            mtvPage.setText("" + values[0]);    // 获取 publishProgress((int)ratio)的values
            proDialog.setProgress(values[0]);
        }
         
        @Override
        protected void onPostExecute(String result) {   // 可以与UI控件交互
            mtvPage.setText(result);
            proDialog.dismiss();
        }
    }
}