HttpClient方式下载apk文件:
private int downloadUpdateFile(String downloadUrl){
int count = 0;
long totalSize = 0;
long downloadSize = 0;
URI uri = null;
HttpGet httpGet = null;
try{
uri = new URI(downloadUrl);
httpGet = new HttpGet(uri);
}catch(URISyntaxException e){
String encodeUrl = downloadUrl.replace(' ', '+');
httpGet = new HttpGet(encodeUrl);
e.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
FileOutputStream fos = null;
InputStream in = null;
try{
httpResponse = httpClient.execute(httpGet);
if(httpResponse != null){
int stateCode = httpResponse.getStatusLine().getStatusCode();
if(stateCode == HttpStatus.SC_OK){
HttpEntity entity = httpResponse.getEntity();
if(entity != null){
totalSize = entity.getContentLength();//获取总大小
int step = (int) (totalSize/1024/100);
//判断内存可用
if(memoryAvailable(totalSize)){
in = entity.getContent();
if(in != null){
fos = new FileOutputStream(updateFile,false);//updateFile是创建的apk要保存的文件file路径
byte buffer[] = new byte[1024];
int readsize = 0;
while((readsize = in.read(buffer))>0){
fos.write(buffer,0,readsize);
downloadSize +=readsize;
count +=1;
if(count==step){
publishProgress(count);//更新界面(AsyncTask)
count = 0;
}
}
fos.flush();
if(totalSize>=downloadSize){
return DOWNLOAD_COMPLETE;
}else{
return DOWNLOAD_FAIL;
}
}
}
else{
if(httpGet != null){
httpGet.abort();
}
return DOWNLOAD_NOMEMORY;
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(fos != null){
fos.close();
}
if(in != null){
in.close();
}
}catch(IOException e){
e.printStackTrace();
}
if(httpClient !=null){
httpClient.getConnectionManager().shutdown();
}
}
return DOWNLOAD_FAIL;
}
//
判断内存
private boolean memoryAvailable(long fileSize){
fileSize += (1024<<10);
ActivityManager am = (ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE);
MemoryInfo mi = new MemoryInfo();
am.getMemoryInfo(mi);
long l = mi.availMem;
if(l>fileSize){
createFile();//创建要保存的地址文件的方法
return true;
}else{
return false;
}
}
********************************************************************************************************************
HttpURLConnection下载apk
private int downloadFileURLConnection(String appurl){
byte[] getData;
InputStream inputStream = null;
createFile();//创建文件路径的方法
FileOutputStream fos;
try {
URL url = new URL(appurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
conn.setRequestProperty("Accept-Encoding", "identity");//不设置会有中文乱码情况
int total = conn.getContentLength();//获取总大小
//得到输入流
inputStream = conn.getInputStream();
//获取自己数组
getData = readInputStream(inputStream,total);
fos = new FileOutputStream(updateFile);//updateFile创建的apk文件路径(是File对象类型)
fos.write(getData);
if (fos != null) {
fos.close();
}
if (inputStream != null) {
inputStream.close();
}
return DOWNLOAD_COMPLETE;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return DOWNLOAD_FAIL;
}
//流转换成byte数组
两种方法都写在了继承AsyncTask的类里,所以可以直接调用publishProgress()方法更新加载进度界面。public byte[] readInputStream(InputStream inputStream,int total) throws IOException { int step = (int) Math.ceil(total/1024/100); byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); count +=1; if(count==step){ publishProgress(count);//更新界面(AsyncTask) count = 0; } } bos.close(); return bos.toByteArray(); }
**************************************************************************************************************
网络获取.json后缀文件:
private static String updateCheckUrl = "http://192.168.1.199:8081/update.json";
try{ URL url = new URL(updateCheckUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("contentType", "GBK"); conn.setConnectTimeout(10*1000); conn.setRequestMethod("POST"); int code = conn.getResponseCode(); if(code == 200){ InputStream inputStream = conn.getInputStream(); String result = MyUtils.streamToString(inputStream); JSONObject object = new JSONObject(result); int newCode = object.getInt("serverFlag");//获取.json文件中json数据的方式 //其他逻辑操作。。。 handler.sendEmptyMessage(SUCCESS); }else{ handler.sendEmptyMessage(FAIL); } } }catch(Exception e){ e.printStackTrace(); handler.sendEmptyMessage(EXC); }
网络请求是耗时操作,代码是在子线程中执行的。