-1

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?

Thanks!

jdie8274j
  • 155
  • 1
  • 10
  • Why don't you try it? – vanje Feb 08 '16 at 13:46
  • Because I'm unable to try it right now and I'd like to know how it works. I know that when there is a direct link I already have the location of the file, but when it is a query string, it is up to the server to return the location of the as content. I was curious how this works. – jdie8274j Feb 08 '16 at 13:58

2 Answers2

0

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.

Ferrybig
  • 18,194
  • 6
  • 57
  • 79
0

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 {
    request.reset();
}
CroWell
  • 606
  • 8
  • 15
  • many thanks for a useful response! With this particular resource, I am getting a 302 sent back from the query with the location. Would url.openStream() automatically resolve to the location? Or would I have to do something like you have there? – jdie8274j Feb 08 '16 at 14:32
  • unfortunately, as I mentioned using `url.openStream()` you'll need to handle 3xx statuses and follow these redirects manually in some cyclic manner. `HttpClients.createDefault()` follows redirects by default and do many useful things, look at official docs they are pretty user-friendly. – CroWell Feb 08 '16 at 14:42