ANdroid如何实现网络重定向以及使用DownLoadManager类下载

来源:互联网 发布:php高级面试题 编辑:程序博客网 时间:2024/05/14 17:54

1.功能脚本:

package com.talkweb.securitypay.test;


import java.io.IOException;
import java.net.URI;


import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.ProtocolException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.RedirectHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;


public class HttpClientURLRedirectTest {
  
    /** 
     * Http URL重定向 
     */  
    public static String redirect02(String url) {  
    DefaultHttpClient httpclient = null;  
        //String url = "http://api.np.mobilem.360.cn/redirect/down/?from=360gamecenter&sid=910959";  
        try {  
            httpclient = new DefaultHttpClient();  
            httpclient.setRedirectHandler(new RedirectHandler() {


@Override
public URI getLocationURI(HttpResponse response,
HttpContext context) throws ProtocolException {
// TODO Auto-generated method stub
return null;
}


@Override
public boolean isRedirectRequested(HttpResponse response,
HttpContext context) {
// TODO Auto-generated method stub
return false;
}
            
            });
            
//            httpclient.setRedirectStrategy(new RedirectStrategy() { //设置重定向处理方式  
//  
//                @Override  
//                public boolean isRedirected(HttpRequest arg0,  
//                        HttpResponse arg1, HttpContext arg2)  
//                        throws ProtocolException {  
//  
//                    return false;  
//                }  
//  
//                @Override  
//                public HttpUriRequest getRedirect(HttpRequest arg0,  
//                        HttpResponse arg1, HttpContext arg2)  
//                        throws ProtocolException {  
//  
//                    return null;  
//                }  
//            });  
  
            // 创建httpget.  
            HttpGet httpget = new HttpGet(url);  
            // 执行get请求.  
            HttpResponse response = httpclient.execute(httpget);  
  
            int statusCode = response.getStatusLine().getStatusCode();  
            if (statusCode == HttpStatus.SC_OK) {  
                // 获取响应实体  
                HttpEntity entity = response.getEntity();  
                if (entity != null) {  
                    // 打印响应内容长度  
                    System.out.println("Response content length: "  
                            + entity.getContentLength());  
                    // 打印响应内容  
                    System.out.println("Response content: "  
                            + EntityUtils.toString(entity));  
                }  
            } else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY  
                    || statusCode == HttpStatus.SC_MOVED_PERMANENTLY) {  
                  
                System.out.println("当前页面发生重定向了---");  
                  
                Header[] headers = response.getHeaders("Location");  
                if(headers!=null && headers.length>0){  
                    String redirectUrl = headers[0].getValue();  
                    System.out.println("重定向的URL:"+redirectUrl);  
                      
                    redirectUrl = redirectUrl.replace(" ", "%20");  
                    return redirectUrl;
                    //get(redirectUrl);  
                }  
            }  
  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (ParseException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            // 关闭连接,释放资源  
            httpclient.getConnectionManager().shutdown();  
        }  
        return null;
    }  
  
    /** 
     * 发送 get请求 
     */  
    private static void get(String url) {  
  
        HttpClient httpclient = new DefaultHttpClient();  
  
        try {  
            // 创建httpget.  
            HttpGet httpget = new HttpGet(url);  
            System.out.println("executing request " + httpget.getURI());  
            // 执行get请求.  
            HttpResponse response = httpclient.execute(httpget);  
              
            // 获取响应状态  
            int statusCode = response.getStatusLine().getStatusCode();  
            if(statusCode==HttpStatus.SC_OK){  
                // 获取响应实体  
                HttpEntity entity = response.getEntity();  
                if (entity != null) {  
                    // 打印响应内容长度  
                    System.out.println("Response content length: "  
                            + entity.getContentLength());  
                    // 打印响应内容  
                    System.out.println("Response content: "  
                            + EntityUtils.toString(entity));  
                }  
            }  
              
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (ParseException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            // 关闭连接,释放资源  
            httpclient.getConnectionManager().shutdown();  
        }  
    }  
}

2.获得网络重定向后的uri:


AsyncTask mTask;
static String Result_new = ""; 
class UrlRedirectTask extends AsyncTask<Void, Void, String> {


@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
//TextView tv = (TextView)findViewById(R.id.);
//String url = (String)tv.getText();
String url = "http://api.np.mobilem.360.cn";
String redirectUrl = HttpClientURLRedirectTest.redirect02(url);//("/redirect/down/?from=360gamecenter&sid=910959");
return redirectUrl;
}


protected void onPostExecute(String result) {
//TextView tv = (TextView)findViewById("1234");
//tv.setText(result);
Result_new = result;
}
}

3.把重定向以后的uri作为下载apk的链接地址,用DownLoadManage类来下载指定的apk包:

demo:

SDK在API Level 9中加入了DownloadManager服务,可以将长时间的下载任务交给系统,完全由系统管理。直接看实例代码:
[java] view plaincopy
  1. package com.hebaijun.downloadtest;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4. import java.net.URLEncoder;  
  5.   
  6. import android.app.Activity;  
  7. import android.app.DownloadManager;  
  8. import android.app.DownloadManager.Request;  
  9. import android.content.BroadcastReceiver;  
  10. import android.content.Context;  
  11. import android.content.Intent;  
  12. import android.content.IntentFilter;  
  13. import android.content.SharedPreferences;  
  14. import android.database.Cursor;  
  15. import android.net.Uri;  
  16. import android.os.Bundle;  
  17. import android.preference.PreferenceManager;  
  18. import android.util.Log;  
  19. import android.webkit.MimeTypeMap;  
  20.   
  21. public class DownloadTestActivity extends Activity {  
  22.     private DownloadManager downloadManager;  
  23.     private SharedPreferences prefs;  
  24.     private static final String DL_ID = "downloadId";  
  25.     /** Called when the activity is first created. */  
  26.     @Override  
  27.     public void onCreate(Bundle savedInstanceState) {  
  28.         super.onCreate(savedInstanceState);  
  29.         setContentView(R.layout.main);  
  30.         downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);  
  31.         prefs = PreferenceManager.getDefaultSharedPreferences(this);   
  32.     }  
  33.     @Override  
  34.     protected void onPause() {  
  35.         // TODO Auto-generated method stub  
  36.         super.onPause();  
  37.         unregisterReceiver(receiver);  
  38.     }  
  39.     @Override  
  40.     protected void onResume() {  
  41.         // TODO Auto-generated method stub  
  42.         super.onResume();  
  43.         if(!prefs.contains(DL_ID)) {   
  44.             String url = "http://10.0.2.2/android/film/G3.mp4";  
  45.             //开始下载   
  46.             Uri resource = Uri.parse(encodeGB(url));   
  47.             DownloadManager.Request request = new DownloadManager.Request(resource);   
  48.             request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);   
  49.             request.setAllowedOverRoaming(false);   
  50.             //设置文件类型  
  51.             MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();  
  52.             String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));  
  53.             request.setMimeType(mimeString);  
  54.             //在通知栏中显示   
  55.             request.setShowRunningNotification(true);  
  56.             request.setVisibleInDownloadsUi(true);  
  57.             //sdcard的目录下的download文件夹  
  58.             request.setDestinationInExternalPublicDir("/download/""G3.mp4");  
  59.             request.setTitle("移动G3广告");   
  60.             long id = downloadManager.enqueue(request);   
  61.             //保存id   
  62.             prefs.edit().putLong(DL_ID, id).commit();   
  63.         } else {   
  64.             //下载已经开始,检查状态  
  65.             queryDownloadStatus();   
  66.         }   
  67.   
  68.         registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));  
  69.     }  
  70.       
  71.     /** 
  72.      * 如果服务器不支持中文路径的情况下需要转换url的编码。 
  73.      * @param string 
  74.      * @return 
  75.      */  
  76.     public String encodeGB(String string)  
  77.     {  
  78.         //转换中文编码  
  79.         String split[] = string.split("/");  
  80.         for (int i = 1; i < split.length; i++) {  
  81.             try {  
  82.                 split[i] = URLEncoder.encode(split[i], "GB2312");  
  83.             } catch (UnsupportedEncodingException e) {  
  84.                 e.printStackTrace();  
  85.             }  
  86.             split[0] = split[0]+"/"+split[i];  
  87.         }  
  88.         split[0] = split[0].replaceAll("\\+""%20");//处理空格  
  89.         return split[0];  
  90.     }  
  91.       
  92.     private BroadcastReceiver receiver = new BroadcastReceiver() {   
  93.         @Override   
  94.         public void onReceive(Context context, Intent intent) {   
  95.             //这里可以取得下载的id,这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听  
  96.             Log.v("intent"""+intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));  
  97.             queryDownloadStatus();   
  98.         }   
  99.     };   
  100.       
  101.     private void queryDownloadStatus() {   
  102.         DownloadManager.Query query = new DownloadManager.Query();   
  103.         query.setFilterById(prefs.getLong(DL_ID, 0));   
  104.         Cursor c = downloadManager.query(query);   
  105.         if(c.moveToFirst()) {   
  106.             int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));   
  107.             switch(status) {   
  108.             case DownloadManager.STATUS_PAUSED:   
  109.                 Log.v("down""STATUS_PAUSED");  
  110.             case DownloadManager.STATUS_PENDING:   
  111.                 Log.v("down""STATUS_PENDING");  
  112.             case DownloadManager.STATUS_RUNNING:   
  113.                 //正在下载,不做任何事情  
  114.                 Log.v("down""STATUS_RUNNING");  
  115.                 break;   
  116.             case DownloadManager.STATUS_SUCCESSFUL:   
  117.                 //完成  
  118.                 Log.v("down""下载完成");  
  119.                 break;   
  120.             case DownloadManager.STATUS_FAILED:   
  121.                 //清除已下载的内容,重新下载  
  122.                 Log.v("down""STATUS_FAILED");  
  123.                 downloadManager.remove(prefs.getLong(DL_ID, 0));   
  124.                 prefs.edit().clear().commit();   
  125.                 break;   
  126.             }   
  127.         }  
  128.     }  
  129. }  

最后需要的权限是:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
如果需要隐藏下载工具的提示和显示,修改代码:
request.setShowRunningNotification(false);
request.setVisibleInDownloadsUi(false);
加入下面的权限:
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>



具体的使用如下:


public void DownLoadApk() 
{
Uri resource = Uri.parse(encodeGB(Result_new)); //Result_new就是重定向以后的url
        DownloadManager.Request request = new DownloadManager.Request(resource);   
       // request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI );   //Request.NETWORK_MOBILE | Request.NETWORK_WIFI
       // request.setAllowedNetworkTypes(0);
        request.setAllowedOverRoaming(true);   
        //设置文件类型  
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();  
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(Result_new));  
        request.setMimeType(mimeString);  
        //在通知栏中显示   
        request.setShowRunningNotification(true);  
        request.setVisibleInDownloadsUi(true);  
        //sdcard的目录下的download文件夹  
        request.setDestinationInExternalPublicDir("/download/", "tiantian.apk");
        filePath = getSDPath() + "/download/tiantian.apk";
        request.setTitle("爸爸去哪儿 官方中文版");
        downloadId = downloadManager.enqueue(request);   
        
        queryDownloadStatus();
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

public String encodeGB(String string)  
    {  
        //转换中文编码  
        String split[] = string.split("/");  
        for (int i = 1; i < split.length; i++) {  
            try {  
                split[i] = URLEncoder.encode(split[i], "GB2312");  
            } catch (UnsupportedEncodingException e) {  
                e.printStackTrace();  
            }  
            split[0] = split[0]+"/"+split[i];  
        }  
        split[0] = split[0].replaceAll("\\+", "%20");//处理空格  
        return split[0];  
    }  
      
    private BroadcastReceiver receiver = new BroadcastReceiver() {   
        @Override   
        public void onReceive(Context context, Intent intent) {   
            //这里可以取得下载的id,这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听  
            Log.v("intent", "" + intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));  
            queryDownloadStatus();   
        }   
    };   
      
    private void queryDownloadStatus() {   
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadId);   
        Cursor c = downloadManager.query(query);   
        if(c.moveToFirst()) {   
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));   
            switch(status) {   
            case DownloadManager.STATUS_PAUSED:   
                Log.v("download", "STATUS_PAUSED");  
            case DownloadManager.STATUS_PENDING:   
                Log.v("download", "STATUS_PENDING");  
            case DownloadManager.STATUS_RUNNING:   
                Log.v("download", "STATUS_RUNNING");  
                break;   
            case DownloadManager.STATUS_SUCCESSFUL:   
                Log.v("download", "下载完成");
                Toast.makeText(UnityPlayer.currentActivity, "下载成功", Toast.LENGTH_LONG).show();
               // mUnityPlayer.UnitySendMessage("_GameData", "SetLoadPararmeter","");
                Log.e("download","has Load  OK!!!");
                c = downloadManager.query(new DownloadManager.Query().setFilterById(downloadId));
                c.moveToFirst();
                String path = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                Log.d("download", path);
                installApk(path);
                break;   
            case DownloadManager.STATUS_FAILED:   
                Log.v("download", "STATUS_FAILED");  
                downloadManager.remove(prefs.getLong(DL_ID, 0));   
                break;   
            }   
        }  
    }
    
    public static String getSDPath(){
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
if (sdCardExist) {
sdDir = Environment.getExternalStorageDirectory();
}
return sdDir.getAbsolutePath();
}
    
    public void installApk(String filePath) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        File file = new File(filePath);
        i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    }





0 0
原创粉丝点击