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();
}
}
}
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;
}
}
@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服务,可以将长时间的下载任务交给系统,完全由系统管理。
直接看实例代码:
- 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;
- }
- }
- }
- }
最后需要的权限是:
<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));
}
{
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);
}
{
//转换中文编码
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);
}