使用場景:用tomcat搭建了一個文件服務器,然后在安卓端去下載文件。
使用技術:使用 HttpURLConnection 建立http連接,并下載
package com.example.facecompare.FaceApi;import android.content.Context;
import android.util.Log;import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;public class ModelDownload {/** 獲取http連接處理類HttpURLConnection*/private HttpURLConnection getConnection(String strUrl){URL url;HttpURLConnection urlcon = null;try {url = new URL(strUrl);urlcon = (HttpURLConnection) url.openConnection();} catch (Exception e) {e.printStackTrace();}return urlcon;}/** 寫文件到sd卡 demo* 前提需要設置模擬器sd卡容量,否則會引發EACCES異常* 先創建文件夾,在創建文件*/public boolean down2sd(String strUrl, String filename, downhandler handler){HttpURLConnection urlcon = getConnection(strUrl);if (urlcon == null){return false;}File file = new File(filename);FileOutputStream outputStream = null;try {int currentSize =0;int totalSize =0;InputStream inputStream = urlcon.getInputStream();if (200 != urlcon.getResponseCode()){return false;}totalSize = urlcon.getContentLength();outputStream = new FileOutputStream(file);byte[] buffer = new byte[1024*10];while (true) {int iReadSize = inputStream.read(buffer);if (-1 == iReadSize){break;}outputStream.write(buffer,0,iReadSize);//同步更新數據currentSize = currentSize+iReadSize;handler.setSize(currentSize,totalSize);}inputStream.close();} catch (Exception e) {return false;} finally {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}return true;}/** 內部回調接口類*/public abstract static class downhandler{public abstract void setSize(int currentSize,int totalSize);}
}
使用方法:
ModelDownload load = new ModelDownload();load.down2sd("http://192.168.31.16:8080/download/"+modelName,storagePath,new ModelDownload.downhandler(){@Overridepublic void setSize(int currentSize, int totalSize) {item.put("DownState",currentSize+"/"+totalSize);Message mes = mHandle.obtainMessage();mes.what = 100;mHandle.sendMessage(mes);}});
?
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态