public static void downloadHttpFile(String sURL,String folder, String sFilePath){
try {
// HttpServletResponse response = null;
// response.setHeader( "Content-Disposition", "attachment;filename=" + new String( sURL.getBytes("UTF-8"), "ISO8859-1" ) );
int nStartPos = 0;
int nRead = 0;
URL url = new URL(sURL);
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("HEAD");
long nEndPos = getFileSize(sURL);
// File file = new File(folder);
// file.mkdir();
RandomAccessFile oSavedFile = new RandomAccessFile(folder+sFilePath, "rw");
httpConnection.setRequestProperty("User-Agent", "Internet Explorer");
String sProperty = "bytes=" + nStartPos + "-";
httpConnection.setRequestProperty("RANGE", sProperty);
//System.out.println(sProperty);
InputStream input = httpConnection.getInputStream();
// ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] b = new byte[4*1024];
while ((nRead = input.read(b, 0, 1024)) > 0 && nStartPos < nEndPos ) {//((length = in.read(b, offset, 1024)) != -1)
oSavedFile.write(b, 0, nRead);
nStartPos += nRead;
}
oSavedFile.close();
httpConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取文件大小
* @param sURL
* @return
*/
public static long getFileSize(String sURL) {
int nFileLength = -1;
try {
String newUrl1 = sURL.substring(0,sURL.lastIndexOf("/")+1);
String newUrl2 = sURL.substring(sURL.lastIndexOf("/")+1);
String newurl = newUrl1 + URLEncoder.encode(newUrl2, "UTF-8");
URL url = new URL(newurl);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestProperty("User-Agent", "Internet Explorer");
httpConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt;NetFox)");
long connSize = httpConnection.getContentLength();
long responseCode = httpConnection.getResponseCode();
httpConnection.getInputStream();
if (responseCode >= 400) {
System.err.println("Error Code : " + responseCode);
return -2; // -2 represent access is error
}
String sHeader;
for (int i = 1;; i++) {
sHeader = httpConnection.getHeaderFieldKey(i);
if (sHeader != null) {
if (sHeader.equals("Content-Length")) {
nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader));
break;
}
} else
break;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println(nFileLength);
return nFileLength;
}
这是我下载文件的代码。
测试url我获取的文件长度是4.7K下载下来文件格式受损,无法打开,我通过右键-另存为文件大小为28K。是不是我的获取文件大小错误了。我已经找了很多方法。都不管用,求大神帮我看看这是什么原因。