我的專案需要在linux下,下載windows檔案服務器的檔案并決議,結果下載總是失敗。
檔案為:http://192.178.1.123:80/223/測驗檔案.xlsx.
下載方式為:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.apache.log4j.Logger;
import com.talkweb.entity.CustomException;
/**
* Java原生的API可用于發送HTTP請求,即java.net.URL、java.net.URLConnection,這些API很好用、很常用,
* 但不夠簡便;
*
* 1.通過統一資源定位器(java.net.URL)獲取連接器(java.net.URLConnection) 2.設定請求的引數 3.發送請求
* 4.以輸入流的形式獲取回傳內容 5.關閉輸入流
*
*
*/
public class HttpConnectionUtil {
private static Logger logger = Logger.getLogger(HttpConnectionUtil.class);
/**
*
* @param urlPath 下載路徑
* @param fileSavePath 下載存放目錄,包含檔案名
* @return 回傳下載檔案
* @throws Exception
*/
public static File downloadFile(String urlPath, String fileSavePath) throws Exception {
urlPath = http://192.178.1.123:80/223/測驗檔案.xlsx;//windows服務器
logger.info("進入下載檔案工具類");
File file = null;
BufferedInputStream bin = null;
OutputStream out = null;
try {
// 統一資源
URL url = new URL(urlPath);
// 連接類的父類,抽象類
URLConnection urlConnection = url.openConnection();
// http的連接類
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
// 設定請求的方法,默認是GET
httpURLConnection.setRequestMethod("GET");
// 設定字符編碼
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打開到此 URL 參考的資源的通信鏈接(如果尚未建立這樣的連接)。
httpURLConnection.connect();
// 檔案大小
int fileLength = httpURLConnection.getContentLength();
// 檔案名
String filePathUrl = httpURLConnection.getURL().getFile();
String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
fileFullName = fileFullName.substring(fileFullName.lastIndexOf("/") + 1);
logger.info("開始下載檔案:" + fileFullName);
logger.info("file length---->" + fileLength);
url.openConnection();
bin = new BufferedInputStream(httpURLConnection.getInputStream());
String path = fileSavePath;
file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
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);
// 列印下載百分比
if ((len * 100 / fileLength)>50&&(len * 100 / fileLength)<55) {
logger.info("下載了-------> " + len * 100 / fileLength + "%");
}else if ((len * 100 / fileLength)>=98) {
logger.info("下載了-------> " + len * 100 / fileLength + "%");
}
//logger.info("下載了-------> " + len * 100 / fileLength + "%");
}
return file;
} catch (Exception e) {
// TODO Auto-generated catch block
throw new CustomException(e.toString()+"檔案下載例外,請檢查下載鏈接$$"+urlPath);
} finally {
if (bin!=null) {
bin.close();
}
if (out!=null) {
out.close();
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/44481.html
標籤:應用程序開發區
上一篇:linux tcp連接 ESTABLISHED狀態過多
下一篇:C++代碼core
