0

I am trying to understand when to use URLConnection Class & when to use HttpURLConnection class. On doing some research, I came to know that URLConnection is used for nonHTTP connections & HttpURLConnection is used for specific HTTP connections. Can someone help me to know that what these nonHTTP connections refer to ?

PS - Please note that my qn is not regarding inheritance relationship of URLConnection Class & HttpURLConnection class.

It is regarding what do we mean by nonHTTP connections (that can be handled by URLConnection Class). Is nonHTTP connection means a datagram connection or ftp connection or something else.Refer below website:

https://www.experts-exchange.com/questions/21420009/URLConnection-and-HttpURLConnection.html

ASharma7
  • 726
  • 3
  • 8
  • 27
  • See https://stackoverflow.com/questions/3920419/difference-between-urlconnection-httpurlconnection-and-httpsurlconnection – Benjamin Maurer Aug 25 '18 at 12:56
  • Possible duplicate of [Difference between URLConnection, HttpURLConnection and HttpsURLConnection](https://stackoverflow.com/questions/3920419/difference-between-urlconnection-httpurlconnection-and-httpsurlconnection) – Benjamin Maurer Aug 25 '18 at 12:56
  • @BenjaminMaurer I have rephrased my qn. Have a look. – ASharma7 Aug 25 '18 at 13:05

1 Answers1

0

A URLConnection is an abstract class, representing any connection to an URL.

A HttpURLConnecton IS a URLConnection (subclass) and offers more methods.

That being said, you could open a URL with the HTTP protocol and assign the return value to a URLConnection, but you'd be missing the more specific methods.

You can open a URL to an ftp resource, or anything else and assign the result to a URLConnection, but it might not support the underlying protocol. For example, FTP support is very limited.

See the documentation for URL.openConnection():

If for the URL's protocol (such as HTTP or JAR), there exists a public, specialized URLConnection subclass belonging to one of the following packages or one of their subpackages: java.lang, java.io, java.util, java.net, the connection returned will be of that subclass. For example, for HTTP an HttpURLConnection will be returned, and for JAR a JarURLConnection will be returned.

So, yes, use HttpURLConnection for HTTP connection and any specialized URLConnection you have, or use the raw URLConnection otherwise. That being said, it depends with which protocol you want to work - you might need a more complete client for any non-trivial protocol.

Benjamin Maurer
  • 3,602
  • 5
  • 28
  • 49