Usage scenario: use Tomcat to build a file server, and then download files in the Android terminal.
Use technology: use HttpURLConnection to establish HTTP connection, and download
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 {/* * 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; }
/* * Write files to sd card demo * Before setting the sd card capacity of the emulator, otherwise EACCES will be raised. */ 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); }Copy the code
} How to use:
ModelDownload load = new ModelDownload(); The load. Down2sd (" http://192.168.31.16:8080/download/ "+ modelName storagePath, new ModelDownload. Downhandler () {@ Override public void setSize(int currentSize, int totalSize) { item.put("DownState",currentSize+"/"+totalSize); Message mes = mHandle.obtainMessage(); mes.what = 100; mHandle.sendMessage(mes); }Copy the code