I Wanted to download one zip file from one URL, for that I Used the below code to open an URL and download one zip file from .But what happens is I am getting following exception
java.net.UnknownHostException: www.abc.com
So I just did some reasearch and guessed that could be the problem of certficate and generated the certificate by using below keytool command
keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048
After that I set the location of generated keystore.jks file by using the following code
System.setProperty("javax.net.ssl.trustStore","C:\\Programme\\Java\\jdk1.6.0_31\\jre\\bin\\keystore.jks");
After running the code, still I am getting the same exception
java.net.UnknownHostException: www.abc.com
Any idea how to ressolve? I am able to access this site from the Browser.
My full code below:
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);
}
}
I tried the below code. That throws unknown host exception.
InetAddress inetAddress = InetAddress.getByName("http://www.google.com");
String ipAddress = inetAddress.getHostAddress().toString()'
System.out.println(ipAddress );
trywith resource (that is if you are using JDK 7) - that will eliminate the need forfinally.