1. 程式人生 > >javaweb 遠端檔案http下載

javaweb 遠端檔案http下載

package ***.**;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;  
  
public class HttpDownloadUtil {  
	public static void  downLoadFromUrl(String urlStr,String fileName,HttpServletResponse response) throws IOException{  
		  
	//URL url = new URL(urlStr); 
	//Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("ip", 埠));//設定代理
	//HttpURLConnection uc = (HttpURLConnection)url.openConnection(proxy);  
	urlStr=urlStr.replaceAll("\\\\", "/");  
        URL url = new URL(urlStr);    
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
         //設定超時間為3秒  
        conn.setConnectTimeout(3*1000);  
        //防止遮蔽程式抓取而返回403錯誤  
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
  
        //得到輸入流  
        InputStream inputStream = conn.getInputStream();    
        //獲取自己陣列  
        byte[] getData = readInputStream(inputStream);      
   
        response.reset();
	response.setContentType("application/octet-stream; charset=utf-8");
	response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859_1"));
        //獲取響應報文輸出流物件  
	OutputStream out =response.getOutputStream();      
	out.write(getData);  
         out.flush();  
         out.close();  
  
    }
	
	public static void  download(String urlStr,  OutputStream out) throws IOException{  
		urlStr=urlStr.replaceAll("\\\\", "/");  
        URL url = new URL(urlStr);    
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
        conn.setConnectTimeout(3*1000);  
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
        InputStream inputStream = conn.getInputStream();    
        byte[] getData = readInputStream(inputStream);      
        out.write(getData);  
        out.flush();  
        out.close();  
  
    }
	
	public static String post(String url, String method, Map<String, String> params) throws IOException{  
        URL u = new URL(url);
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
        	conn = (HttpURLConnection)u.openConnection();
        	conn.setRequestMethod(method);
        	conn.setUseCaches(false);
        	conn.setDoOutput(true);
        	conn.setDoInput(true);
            conn.setConnectTimeout(3*1000);  
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
            outputStream = conn.getOutputStream();
            StringBuilder sb = new StringBuilder();
            if (url.indexOf("?") < 0) {
            	sb.append("?");
            }
            Iterator<Entry<String, String>> it = params.entrySet().iterator();
            while (it.hasNext()) {
            	Entry<String, String> entry = it.next();
            	sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            outputStream.write(sb.toString().getBytes());
            inputStream = conn.getInputStream();
            byte[] getData = readInputStream(inputStream);
            return new String(getData, StandardCharsets.UTF_8);
        } finally {
        	IOUtils.closeQuietly(outputStream);
        	IOUtils.closeQuietly(inputStream);
        	IOUtils.close(conn);
        }
    }
  
    /** 
     * 從輸入流中獲取位元組陣列 
     * @param inputStream 
     * @return 
     * @throws IOException 
     */  
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {    
        byte[] buffer = new byte[1024];    
        int len = 0;    
        ByteArrayOutputStream bos = new ByteArrayOutputStream();    
        while((len = inputStream.read(buffer)) != -1) {    
            bos.write(buffer, 0, len);    
        }    
        bos.close();    
        return bos.toByteArray();    
    }
    
    public static String fileNameEncode(String name) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < name.length(); i++) {
			char c = name.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes(StandardCharsets.UTF_8);
				} catch (Exception ex) {
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}
    
    public static String fileNameEncode(String name, String userAgent) throws UnsupportedEncodingException {
		if (userAgent != null && userAgent.toLowerCase().indexOf("firefox") >= 0) {
			return "=?UTF-8?B?" + (new String(Base64.encodeBase64(name.getBytes("UTF-8")))) + "?=";
		} else {
			return fileNameEncode(name);
		}
    }
}