ANdroid如何实现网络重定向以及使用DownLoadManager类下载
1.功能脚本:
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:
@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:
- package com.hebaijun.downloadtest;
- import java.io.UnsupportedEncodingException;
- import java.net.URLEncoder;
- import android.app.Activity;
- import android.app.DownloadManager;
- import android.app.DownloadManager.Request;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.content.SharedPreferences;
- import android.database.Cursor;
- import android.net.Uri;
- import android.os.Bundle;
- import android.preference.PreferenceManager;
- import android.util.Log;
- import android.webkit.MimeTypeMap;
- public class DownloadTestActivity extends Activity {
- private DownloadManager downloadManager;
- private SharedPreferences prefs;
- private static final String DL_ID = "downloadId";
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
- prefs = PreferenceManager.getDefaultSharedPreferences(this);
- }
- @Override
- protected void onPause() {
- // TODO Auto-generated method stub
- super.onPause();
- unregisterReceiver(receiver);
- }
- @Override
- protected void onResume() {
- // TODO Auto-generated method stub
- super.onResume();
- if(!prefs.contains(DL_ID)) {
- String url = "http://10.0.2.2/android/film/G3.mp4";
- //开始下载
- Uri resource = Uri.parse(encodeGB(url));
- DownloadManager.Request request = new DownloadManager.Request(resource);
- request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
- request.setAllowedOverRoaming(false);
- //设置文件类型
- MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
- String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
- request.setMimeType(mimeString);
- //在通知栏中显示
- request.setShowRunningNotification(true);
- request.setVisibleInDownloadsUi(true);
- //sdcard的目录下的download文件夹
- request.setDestinationInExternalPublicDir("/download/", "G3.mp4");
- request.setTitle("移动G3广告");
- long id = downloadManager.enqueue(request);
- //保存id
- prefs.edit().putLong(DL_ID, id).commit();
- } else {
- //下载已经开始,检查状态
- queryDownloadStatus();
- }
- registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
- }
- /**
- * 如果服务器不支持中文路径的情况下需要转换url的编码。
- * @param string
- * @return
- */
- 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(prefs.getLong(DL_ID, 0));
- 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("down", "STATUS_PAUSED");
- case DownloadManager.STATUS_PENDING:
- Log.v("down", "STATUS_PENDING");
- case DownloadManager.STATUS_RUNNING:
- //正在下载,不做任何事情
- Log.v("down", "STATUS_RUNNING");
- break;
- case DownloadManager.STATUS_SUCCESSFUL:
- //完成
- Log.v("down", "下载完成");
- break;
- case DownloadManager.STATUS_FAILED:
- //清除已下载的内容,重新下载
- Log.v("down", "STATUS_FAILED");
- downloadManager.remove(prefs.getLong(DL_ID, 0));
- prefs.edit().clear().commit();
- break;
- }
- }
- }
- }
具体的使用如下:
{
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));
}
{
//转换中文编码
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);
}
ANdroid如何实现网络重定向以及使用DownLoadManager类下载相关推荐
- Android快速开发不可或缺的11个工具类(下载)
Android快速开发不可或缺的11个工具类(下载) 源码简介 Android快速开发不可或缺的11个辅助类,其中10个来自张鸿洋的博客,1个是我平时积攒的,复制粘贴到你的项目里,添加上包名就可以直接 ...
- Android 实现播放网络视频 内容附源码下载链接
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...
- Android面试题网络篇
Android面试题网络篇,由本人整理汇总,后续将继续推出系列篇,如果喜欢请持续关注和推荐. 系列文章目录: Android面试题View篇 Android面试题进程篇 Android面试题线程篇 T ...
- Android常用的网络框架介绍和使用
一.选择开源框架的原则 1.学习的成本:对该框架学习的时间长短,文档是否齐全的考虑 2.流行的程度:该开源框架是否流行,github 上 start 的个数,都是我们考量的标准 3.是否还在维护: ...
- Android编程获取网络连接状态及调用网络配置界面
获取网络连接状态 随着3G和Wifi的推广,越来越多的Android应用程序需要调用网络资源,检测网络连接状态也就成为网络应用程序所必备的功能. Android平台提供了ConnectivityMan ...
- Android 实现无网络传输文件(2)
在我的上一篇文章:Android 实现无网络传输文件,我介绍了通过 Wifi Direct(Wifi 直连)实现 Android 设备之间进行文件传输的方法,可以在无移动网络的情况下实现点对点的文件传 ...
- android中怎么网络判断,Android中判断网络是否连接实例详解
Android中判断网络是否连接实例详解 在android中,如何监测网络的状态呢,这个有的时候也是十分重要的,方法如下: public class ConnectionDetector { priv ...
- Android编程获取网络连接状态(3G/Wifi)及调用网络配置界面
http://www.mobiletuts.me 获取网络连接状态 随着3G和Wifi的推广,越来越多的Android应用程序需要调用网络资源,检测网络连接状态也就成为网络应用程序所必备的功能. An ...
- Android设备的网络抓包
Android设备的网络抓包 背景 比如产品有4G和以太网,我们在调试的时候可能相知道看网络是走4G还是以太网,需要通过抓包来确定 2.抓包方案 2.1 采用集线器 此方案可以对比分析多台设备之间 ...
最新文章
- (转)理解android.intent.action.MAIN 与 android.intent.category.LAUNCHER
- mysql+怎样查询最后几条_mysql 查询开头或最后几行
- RabbitMQ——无法连接错误[AmqpConnectException: java.net.ConnectException: Connection refused: connect]解决方案
- TensorFlow安装手册
- Hibernate初探(二)
- 用PHP去掉文件头的Unicode签名(BOM)
- React hook 中的数据获取
- 每个tabpage中都有一个dategridview_每个女人,都有一个礼服梦
- macosx下apache的默认用户为daemon
- mysql 分组查询例子_分组查询GROUP BY用法例子详解
- Exchange Server 2016 独立部署/共存部署 (三)—— 安装Exchange程序
- php调用jssdk转发_php一个文件搞定微信jssdk配置
- 没啥用的纯前端打造一个实时 markdown 编辑器
- 为什么科技互联网公司越来越重视数学?
- 解决方案:集团型施工企业安全生产数字化管理系统
- 前端实现文件上传(点击+拖拽)
- openwrt mysql改密码_openwrt的路由器重置root密码
- 第一代程序员王小波 (送书活动)
- 指纹识别的原理与优势
- 白苹果了怎么办_ios13更新遭遇白苹果了怎么办?