request response 下载文件

自我感觉,这是所有 网络请求框架的雏形.

根据URL下载APK

if (!URLUtil.isNetworkUrl(strPath)) {
        Log.i(this.getClass().getName(), "getDataSource() It's a wrong URL!");
        runException = "error";
        return "error";
    }

    InputStream is = null;
    FileOutputStream fos = null;
    Float apkSize = null;// apk实际大小
    try {
        //Const.getConst().pageRequestUrl+ "mt/MTCon/downloadHelpFile.json"
        URL myURL = new URL(Const.getConst().pageRequestUrl+ "mt/MTCon/downloadHelpFile.json?note=DOWNLOAD_APP");
        URLConnection conn = myURL.openConnection();
        conn.setConnectTimeout(10000);
        conn.connect();
        is = conn.getInputStream();
        if (is == null) {
            throw new RuntimeException("stream is null");
        }
        apkSize = (float) (17*1024(float) conn.getContentLength());// 下载总大小
        String fileEx = strPath.substring(strPath.lastIndexOf(".") + 1, strPath.length())
                .toLowerCase();// 下载文件名
        String fileNa = strPath.substring(strPath.lastIndexOf("/") + 1,
                strPath.lastIndexOf("."));// 下载文件后缀
        // 判断SD卡是否存在,存在则存于SDK,不存在写手机内存
        boolean hasSD = Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);

        Log.i("下载文件", "apkSize="+apkSize);
        Log.i("下载文件", "hasSD="+hasSD);
        // 文件会自动下载保存至“/data/data/[包名]/files/[文件名]
        myTempFile = new File("/data/data/" + activity.getPackageName() + "/files/" + fileNa
                + "." + fileEx);
        //保存到sd卡中

//          myTempFile = new File(Environment.getExternalStorageDirectory()+"/dowload/" + fileNa + "." + fileEx);

//          Log.i("下载文件", "myTempFile="+myTempFile.getAbsolutePath());

        fos = activity.openFileOutput(fileNa + "." + fileEx, Context.MODE_WORLD_WRITEABLE|Context.MODE_WORLD_READABLE);
        float alreadySize = (float) 0;// 已下载的大小
        byte buf[] = new byte[1024];
        do {
            int numread = is.read(buf);
            if (numread <= 0) {
                break;
            }
            fos.write(buf, 0, numread);
            alreadySize = alreadySize + buf.length;
            NumberFormat nf = NumberFormat.getPercentInstance();
            String proportion = nf.format(alreadySize / apkSize);

            // 往UI线程传进度值
            publishProgress(Integer.valueOf(proportion.substring(0, proportion.length() - 1)));

        } while (isRun);

    } catch (Exception e) {
        e.printStackTrace();
        runException = "error";
        return "error";
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
            }
        }

    }

    return null;

根据参数,下载文件

    String readContent=null;    
    DefaultHttpClient httpClient = new DefaultHttpClient();
    CookieStore cookiestore = null;
    HttpUriRequest request = null;
    request = new HttpPost(Const.getConst().pageRequestUrl+ "mt/MTCon/downloadHelpFile.json?note=DOWNLOAD_APP"");
    request.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
            60000);
    request.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    request.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        UrlEncodedFormEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(list, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ((HttpPost) request).setEntity(entity);
    }

    if (cookiestore != null) {
        httpClient.setCookieStore(cookiestore);

    }




    HttpResponse response = null;
    try {
        response = httpClient.execute(request);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }    


     try{
        if (response != null) {    
            //getResponse    
            InputStream in=(InputStream) response.getEntity().getContent();    
            int count = 0;    
            while (count == 0) {    
             count = Integer.parseInt(in.available()+"");//in.available();    
            }    
            byte[] bytes = new byte[count];    
            int readCount = 0; // 已经成功读取的字节的个数    
            while (readCount <= count) {    
             if(readCount == count)break;    
             readCount += in.read(bytes, readCount, count - readCount);    
            }    

            long length_tmp = 1024*1024*1024;  
            long index = 0;// start from zero  
            int readSize;  
          //  byte[] bytes = new byte[1024];   
            while ((readSize = in.read(bytes, (int) index, (int) 1024)) != -1) {  
                length_tmp -= readSize;  
                if (length_tmp == 0) {  
                    break;  
                }  
                index = index + readSize;  
            }  
            //转换成字符串    

            System.out.println("2.Get Response Content():\n"+readContent);    
        }    
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值