Home Ask Login Register

Developers Planet

Your answer is one click away!

jdie8274j February 2016

Read InputStream from file via URL query string

Is it possible to use the java URL.openStream() method to read the file into an input stream when the URL is a query string rather than a direct link to a file? E.g. the code I have is:

URL myURL = new URL("http://www.test.com/myFile.doc");
InputStream is = myURL.openStream(); 

This works fine for a direct file link. But what if the URL was http://www.test.com?file=myFile.doc ? Would I still be able to obtain the file stream from the server response?



Ferrybig February 2016

The URL class works for any url, including:

  • new URL("http://www.example.com/");
  • new URL("file://C/windows/system32/cmd.exe");
  • new URL("ftp://user:password@example.com/filename;type=i");

Its up to the application to do something with the data, for example download the data, or treat it as plain text.

CroWell February 2016

Generally YES, it will work.

But note that URL.openStream() method doesn't follow redirects and not so agile with specifying some additional HTTP behaviours: request type, headers, etc.

I'd recommend to use Apache HTTP Client instead:

final CloseableHttpClient httpclient = HttpClients.createDefault();         
final HttpGet request = new HttpGet("http://any-url");

try (CloseableHttpResponse response = httpclient.execute(request)) {
    final int status = response.getStatusLine().getStatusCode();

    if (status == 200) {
        final InputStream is = response.getEntity().getContent();
    } else {
        throw new IOException("Got " + status + " from server!");
finally {

Post Status

Asked in February 2016
Viewed 2,596 times
Voted 5
Answered 2 times


Leave an answer

Quote of the day: live life