Search code examples
javaapachefilehttpinputstream

Is URL.openStream() the same as respone.getEntity().getContent()?


There is a file that will be downloaded when I make a get request to particular URL. I am able to get InputStream from both ways.

Method 1

Using URL class in java.net package.

java.net.URL url = new URL(downloadFileUrl);
InputStream inputStream = url.openStream();

Method 2

Using Apache's HttpClient class.

org.apache.http.impl.client.CloseableHttpClient httpclient = new CloseableHttpClient();
HttpGet request = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute((HttpUriRequest)request);
InputStream inputStream = response.getEntity().getContent();

Are these methods the same? If not how? Which method is preferred generally or in a specific situation?

The examples I provided are simplistic. Assume I did the neccessary congifurations with the URL and HttpClient objects to get successful response.


Solution

  • Both methods returns the input stream to read from the connection. There isn't difference between these methods. Since HttpClient is third party library, you need to keep a check for any vulnerabilities and keep updating the library.

    Only difference is HttpClient supports only HTTP(s) protocol, whereas URLConnection can be used for other protocols too like FTP

    In terms of functionalities, Apache HttpClient has more fine tuning options than URLConnection