这里我用的是Android的HttpURLConnection来实现的!直接见具体代码吧:
downloadFile方法中两个参数:
urlStr:表示下载目前的链接地址
outputPath:表示下载完成后的文件保存地址
public static boolean downloadFile(String urlStr, String outputPath) { URL url = null; try { url = new URL(urlStr); } catch (Exception e) { return false; } HttpURLConnection httpURLConnection = null; InputStream in = null; FileOutputStream fileOutputStream = null; BufferedInputStream bufferedInputStream = null; BufferedOutputStream bufferedOutputStream = null; try { String protocol = url.getProtocol(); httpURLConnection = (HttpURLConnection) url.openConnection(); // 配置连接属性 httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); // 设置请求头 setRequestProperty(httpURLConnection); // 发送参数 httpURLConnection.setRequestMethod("GET"); long time = System.currentTimeMillis(); // 获取返回数据 int responseCode = httpURLConnection.getResponseCode(); long time1 = System.currentTimeMillis() - time; if (responseCode == HttpURLConnection.HTTP_OK) { String encodingType = httpURLConnection.getContentEncoding(); if (encodingType != null && encodingType.equals("gzip")) { in = new GZIPInputStream(httpURLConnection.getInputStream()); } else { long time0 = System.currentTimeMillis(); in = httpURLConnection.getInputStream(); long time2 = System.currentTimeMillis() - time0; } // 把数据写入内存 fileOutputStream = new FileOutputStream(outputPath); bufferedInputStream = new BufferedInputStream(in); bufferedOutputStream = new BufferedOutputStream(fileOutputStream); byte[] buffer = new byte[1024]; int readLen = 0; while ((readLen = bufferedInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, readLen); bufferedOutputStream.flush(); } return true; } else { // 服务器返回非200 return false; } } catch (Exception e){ Debuger.logD(e.getMessage()); } finally { try { if (fileOutputStream != null) fileOutputStream.close(); if (bufferedOutputStream != null) bufferedOutputStream.close(); if (bufferedInputStream != null) bufferedInputStream.close(); if (in != null) in.close(); } catch (IOException e) { e.printStackTrace(); } // 关闭连接 if (httpURLConnection != null) httpURLConnection.disconnect(); } return false; }
private static void setRequestProperty(HttpURLConnection conn) throws IOException { try { conn.setConnectTimeout(5000);// 设置连接主机超时(单位:毫秒) conn.setReadTimeout(30000);// 设置从主机读取数据超时(单位:毫秒) conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Accept-Encoding", "gzip"); } catch (Exception e) { e.printStackTrace(); } }