从Java下载HTTPS URL中的图像

时间:2014-12-17 12:40:36

标签: java image url https download

我必须做一个显示药物包装图像的应用程序。我发现这个site有一些,但是我试图用Java中的一个小程序下载可用的图像但是失败了。 我认为HTTPS会导致问题。

有办法吗?

编辑:代码和错误

public class DescargarArchivo {

public static void main(String[] args) {
    String url = "https://medicamentos.sanidadmadrid.org/comun/visorCaratulas.aspx?cod=672629";
    String name = "test.jpg";

    String folder = "downloads/";

    File dir = new File(folder);

    if (!dir.exists())
            if (!dir.mkdir())
                    return;

    File file = new File(folder + name);

    try {

            URLConnection conn = new URL(url).openConnection();
            conn.connect();

            System.out.println("\ndownload: \n");
            System.out.println(">> URL: " + url);
            System.out.println(">> Name: " + name);
            System.out.println(">> size: " + conn.getContentLength()
                            + " bytes");

            InputStream in = conn.getInputStream();
            OutputStream out = new FileOutputStream(file);

            int b = 0;

            while (b != -1) {
                    b = in.read();

                    if (b != -1)
                            out.write(b);
            }

            out.close();
            in.close();

            System.out.println("\ncomplete download\n");
    } catch (MalformedURLException e) {
            System.out.println("url: " + url + " invalid");
    } catch (IOException e) {
            e.printStackTrace();
    }
}
}

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)
at com.test.java.net.DescargarArchivo.main(DescargarArchivo.java:34)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
    at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
    at sun.security.validator.Validator.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    ... 12 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Source)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    ... 18 more

4 个答案:

答案 0 :(得分:2)

其实我遇到了类似的问题。我无法从HTTPS服务器下载文件。然后我用这个解决方案解决了这个问题:

  int main()
  {
    int i;
    char a = '?';

    int aCount=0;
    int bCount=0;
    int cCount=0;

    while(a != 'q' && a != 'Q')
    {
      scanf("%c", &a);

      switch(a)
      {
         case 'A':
         case 'a':
           aCount++;
         break;
         case 'B':
         case 'b':
           bCount++;
         break;
         case 'C':
         case 'c':
           cCount++;
         break;
         default:
           puts("Mxm choose A, B, C or Q to quit.");
         break;
       }
    }
    printf("\nA - %d\nB - %d\nC - %d", aCount,bCount,cCount);
  }

希望这会有所帮助...... :)

答案 1 :(得分:1)

您需要设置允许服务器证书的权限。 Here它解释了如何设置以使所有证书都受信任。

答案 2 :(得分:0)

String relativePath = new File(System.getProperty("user.dir")).getAbsolutePath();
String url = "https://google.com";
//Imageoutput is folder within Project and ImageName is name for image
String FileNameOutput = relativePath + File.separator + "ImageOutput" + File.separator + ImageName;

//Just for console output Image Name and URL
try(BufferedInputStream inputStream = new BufferedInputStream(new URL(url).openStream()); 
FileOutputStream fileOS = new FileOutputStream(FileNameOutput)) 
{
    byte data[] = new byte[4096];
    int byteContent;
    while ((byteContent = inputStream.read(data, 0, 4096)) != -1) 
    {
      //Write data to the location
        fileOS.write(data, 0, byteContent);
    }

    //Confirming Image is downloaded in the console
} 

这对我有用

答案 3 :(得分:0)

我认为根本原因是您的代码与服务器之间没有ssl连接

  • 导出站点证书
  • 通过System.getProperties(“ java.home”);打印您的运行时JRE路径;
  • 将证书添加到运行时JRE中,如下所示:

  • cd jrepath \ bin

  • keytool -keystore“ jrepath \ lib \ security \ cacerts”-导入-alias ca-文件 “ certpath”