Android源68,69,70

private class MyAyncTask extends AsyncTask<String, Integer, String>{  
        //初始化UI  
        @Override  
        protected void onPreExecute() {  
            super.onPreExecute();  
            mSeekBar.setProgress(0);  
            mSeekBar.setMax(100);  
 
            mTextView.setText("loading ...");  
        }  
        //后台操作  
        @Override  
        protected String doInBackground(String... params) {  
            try {  
                // 1. 构造URL对象  
                String path = params[0];  
                URL url = new URL(path);   
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();  
 
                urlConnection.setRequestMethod("GET");  
                urlConnection.setConnectTimeout(5000);  
                urlConnection.setRequestProperty("Accept-Encoding", "identity");  
 
                int code = urlConnection.getResponseCode();  
                // 200 OK  302 found 404 not fount 500 内部错误  
                if (code == 200) {  
                    // 获取内容长度,需要指定RequestProperty  
                    int nMaxLen = urlConnection.getContentLength();  
                    int nLen = 0;  
 
                    // 4.1 读取信息  
                    InputStream inputStream = urlConnection.getInputStream();  
                    byte[] bytes = new byte[50];  
                    int iReadSize = 0;  
                    // 创建字节流对象,用于保存输入流的信息  
                    ByteArrayOutputStream byteObj = new ByteArrayOutputStream();  
                    while (iReadSize != -1) {  
                        // 循环读取数据信息,每次读取1024字节,会自动移动指针  
                        // 第二个参数指的值字节数组的起始偏移  
                        iReadSize = inputStream.read(bytes, 0, 50);  
                        if (iReadSize == -1) break;  
                        // 计算已经读取的长度  
                        this.publishProgress((int) (((float) nLen / (float) nMaxLen) * 100));  
                        byteObj.write(bytes, 0, iReadSize);  
 
                    }  
                    inputStream.close();  
                    String strings = new String(byteObj.toByteArray());  
                    return strings;  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
 
            return null;  
        }    
        protected void onProgressUpdate(Integer... values) {  
            super.onProgressUpdate(values);  
            mSeekBar.setProgress(values[0]);  
        }   
        protected void onPostExecute(String s) {  
            super.onPostExecute(s);  
            mTextView.setText(s);  
        }  
    } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值