我正在使用url下载此jar,但下载了0kb文件。我什至使用其他网址,即使ftp网址也能正常工作,问题仅在于此文件。

网址不起作用


  http://jdbc.postgresql.org/download/postgresql-9.2-1002.jdbc4.jar


使用下面的代码。

try
{
    bis = new BufferedInputStream(url.openStream());
    String fileName = DownloadSourceUtils.getUniqueFileName(DownloadSourceConstants.DOWNLOAD_LOCALTION, url.getFile());

    File directory = new File(DownloadSourceConstants.DOWNLOAD_LOCALTION);
    if (! directory.exists()){
        directory.mkdir();
        // If you require it to make the entire directory path including parents,
        // use directory.mkdirs(); here instead.
    }

    fos = new FileOutputStream(DownloadSourceConstants.DOWNLOAD_LOCALTION+File.separator+fileName);

    byte dataBuffer[] = new byte[1024];
    int bytesRead;
    while ((bytesRead = bis.read(dataBuffer, 0, 1024)) != -1)
    {
        fos.write(dataBuffer, 0, bytesRead);
    }
    fos.flush();
    output = url + " downloaded successfully";
    return output;
}
catch (IOException e)
{
    output = e.getMessage();
    return output;
}
finally
{
    if(bis != null)
        bis.close();
    if(fos != null)
        fos.close();
}

最佳答案

我认为这里的问题是URL重定向到另一个HTTPS:

$ curl -i http://jdbc.postgresql.org/download/postgresql-9.2-1002.jdbc4.jar
HTTP/1.1 301 Moved Permanently
Location: https://jdbc.postgresql.org/download/postgresql-9.2-1002.jdbc4.jar
Content-Length: 0
Date: Fri, 16 Nov 2018 14:37:09 GMT
Server: lighttpd/1.4.45
Connection: keep-alive


因此,我会将您的网址更新为https://jdbc.postgresql.org/download/postgresql-9.2-1002.jdbc4.jar
有关Java无法正常运行的原因的详细讨论,请参见URLConnection Doesn't Follow Redirect

10-06 05:05
查看更多