HttpConnectionUtil.java 2.64 KB
package com.topdraw.sohu.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class HttpConnectionUtil {

	private static final Logger log = LoggerFactory
			.getLogger(HttpConnectionUtil.class);

	/**
	 * @param strUrlPath     下载路径
	 * @param strDownloadDir 下载存放目录
	 * @param strDownloadDir 下载文件重命名(null保持原有名字)
	 * @return 返回下载文件
	 */
	public static File downloadFile(String strUrlPath, String strDownloadDir, String strFileName) {
		File file = null;
		try {
			// 统一资源
			URL url = new URL(strUrlPath);
			// 连接类的父类,抽象类
			URLConnection urlConnection = url.openConnection();
			// http的连接类
			HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
			// 设定请求的方法,默认是GET
			httpURLConnection.setRequestMethod("GET");
			// 设置字符编码
			httpURLConnection.setRequestProperty("Charset", "UTF-8");

			httpURLConnection.setRequestProperty("Accept-Encoding", "identity");
			httpURLConnection.setReadTimeout(10000);
			// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
			httpURLConnection.connect();

			// 文件大小
			int fileLength = httpURLConnection.getContentLength();

			// 文件名
			String filePathUrl = strFileName == null ? httpURLConnection.getURL().getFile() : strFileName;
			String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);

			//log.info("file length -> " + fileLength);

			URLConnection con = url.openConnection();

			BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());

			String path = strDownloadDir + File.separatorChar + fileFullName;
			file = new File(path);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			OutputStream out = new FileOutputStream(file);
			int size = 0;
			int len = 0;
			byte[] buf = new byte[1024];
			while ((size = bin.read(buf)) != -1) {
				len += size;
				out.write(buf, 0, size);
				// 打印下载百分比
				// log.info("下载了 -> " + len * 100 / fileLength);
			}
			bin.close();
			out.close();

			if (file.length() != fileLength && fileLength != -1) {
				log.info("file size mismatch: " + fileLength + " -> " + file.length());
				file = null;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
			file = null;
		} catch (IOException e) {
			e.printStackTrace();
			file = null;
		}
		return file;

	}

	public static void main(String[] args) {

	}

}