我想从一个 URL 下载一个 zip 文件,为此我使用下面的代码打开一个 URL 并从中下载一个 zip 文件。但是会发生什么是我得到以下异常
java.net.UnknownHostException: www.abc.com
所以我只是做了一些研究并猜测这可能是证书的问题,并使用下面的 keytool 命令生成了证书
keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048
之后,我使用以下代码设置生成的 keystore.jks 文件的位置
System.setProperty("javax.net.ssl.trustStore","C:\\Programme\\Java\\jdk1.6.0_31\\jre\\bin\\keystore.jks");
运行代码后,我仍然得到相同的异常
java.net.UnknownHostException: www.abc.com
知道如何解决吗?我可以从浏览器访问该站点。
我的完整代码如下:
import java.io.*;
import java.net.*;
public class UrlDownload {
final static int size = 1024;
public static void fileUrl(String fAddress, String localFileName,
String destinationDir) {
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
try {
URL Url;
byte[] buf;
int ByteRead, ByteWritten = 0;
Url = new URL(fAddress);
outStream = new BufferedOutputStream(new FileOutputStream(
destinationDir + "\\" + localFileName));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
System.out.println("Downloaded Successfully.");
System.out.println("File name:\"" + localFileName
+ "\"\nNo ofbytes :" + ByteWritten);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void fileDownload(String fAddress, String destinationDir) {
int slashIndex = fAddress.lastIndexOf('/');
int periodIndex = fAddress.lastIndexOf('.');
String fileName = fAddress.substring(slashIndex + 1);
if (periodIndex >= 1 && slashIndex >= 0
&& slashIndex < fAddress.length() - 1) {
fileUrl(fAddress, fileName, destinationDir);
} else {
System.err.println("path or file name.");
}
}
public static void main(String[] args) {
String url = "http://www.abc.com/coolsolutions/tools/downloads/ntradping.zip";
System.setProperty("javax.net.ssl.trustStore","C:\\Programme\\Java\\jdk1.6.0_31\\jre\\bin\\keystore.jks");
String destAddress = "C:\\downloads";
fileDownload(url,destAddress);
}
}
我尝试了下面的代码。这会引发未知主机异常。
InetAddress inetAddress = InetAddress.getByName("http://www.google.com");
String ipAddress = inetAddress.getHostAddress().toString()'
System.out.println(ipAddress );