zkqloveyu1314 2015-12-28 14:31 采纳率: 0%
浏览 3877

java 通过url地址下载

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。是不是我的获取文件大小错误了。我已经找了很多方法。都不管用,求大神帮我看看这是什么原因。
  • 写回答

1条回答 默认 最新

  • wuheng_1 2015-12-28 14:53
    关注

    制作一个特别格式的测试文件,下载后再对比,用双文件HEX比较工具查问题吧。
    比如以512字节为一块,全部放字符"A",下一块放字符"B",依此类推。

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!