I am trying to download a file from this url, but the code hang at getInputStream(); I type this url in the browser. the url is accessible http://filehost.blob.core.windows.net/firmware/version.txt
What is the cause of it ?
URL url = new URL("http://filehost.blob.core.windows.net/firmware/version.txt");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream(); //hang at this line
int totalSize = urlConnection.getContentLength();
SOLUTION
Use URL
with Scanner
.
CODE
URL url = new URL("http://filehost.blob.core.windows.net/firmware/version.txt");
Scanner s = new Scanner(url.openStream());
while (s.hasNextLine())
System.out.println(s.nextLine());
s.close();
OUTPUT
1.016
NOTE
MalformedURLException
and IOException
must be thrown
or handled.
SOLUTION
Use JAVA NIO .
CODE
URL website = new URL("http://filehost.blob.core.windows.net/firmware/version.txt");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("C:/temp/version.txt");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
OUTPUT
file has been created at c:\\test\\version.txt
with 5 bytes size
NOTE
MalformedURLException
, FileNotFoundException
and IOException
must be thrown
or handled.
I tried your code snippet and could not reproduce your problem - it does not hang for me. I think that your network (configuration) may have some problems and that your code hangs until some timeout occurs.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.