Search code examples
javaurlnetwork-programmingjunithttpconnection

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?

Thanks!


Solution

  • 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();
    }