1. 程式人生 > >java 實現 http 檔案下載

java 實現 http 檔案下載

package com.easemob.server.example.httpclient.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

public
class HttpUtils { /** * LOCAL_PATH 檔案儲存的位置 * fileUrl 待下載檔案地址 * type 檔案型別 jpg,png,mp3... * @return */ public static String FileDown(String LOCAL_PATH,String fileUrl,String type){ InputStream in=null; OutputStream out=null; HttpURLConnection conn=null
; String fileName=null; try { //初始化連線 URL url=new URL(fileUrl); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); //獲取檔名 String disposition=conn.getHeaderField("Content-Disposition"
); if(disposition!=null&&!"".equals(disposition)){ //從頭中獲取檔名 fileName=disposition.split(";")[1].split("=")[1].replaceAll("\"",""); }else{ //從地址中獲取檔名 fileName=fileUrl.substring(fileUrl.lastIndexOf("/")+1); } if(fileName!=null&&!"".equals(fileName)){ //檔名解碼 fileName=URLDecoder.decode(fileName, "utf-8")+".jpg"; }else{ //如果無法獲取檔名,則隨機生成一個 fileName="file_"+(int)(Math.random()*10)+type; } //讀取資料 if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){ byte[] buffer=new byte[2048]; in = conn.getInputStream(); out=new FileOutputStream(new File(LOCAL_PATH,fileName)); int count=0; int finished=0; int size=conn.getContentLength(); while((count=in.read(buffer))!=-1){ if(count!=0){ out.write(buffer,0,count); finished+=count; // System.out.printf("---->%1$.2f%%\n",(double)finished/size*100); }else{ break; } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { out.close(); in.close(); conn.disconnect(); } catch (IOException e) { e.printStackTrace(); } } return fileName; } public static void main(String[] args) { //待下載檔案地址 String fileUrl="http://182.92.228.160:80/otrue-cn/healthmanager/chatfiles/22ecda70-ad43-11e5-9531-d7e3b2ec0d8e"; String LOCAL_PATH="E:/ceshi/"; String type="jpg"; String filename=FileDown(LOCAL_PATH, fileUrl,type); System.out.println(filename); } }