Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use HTTPClient or HttpUrlConnection? [closed]

We're implementing a REST client on JRE 1.4.

Seems two good options for a client REST framework are HttpClient and HttpUrlConnection.

Is there a reason to use HttpClient over the JRE's HttpUrlConnection?

like image 305
Marcus Leon Avatar asked Nov 16 '09 00:11

Marcus Leon


People also ask

Does HttpClient need to be closed?

You do not need to explicitly close the HttpClient, however, (you may be doing this already but worth noting) you should ensure that connections are released after method execution. Edit: The ClientConnectionManager within the HttpClient is going to be responsible for maintaining the state of connections.

Can we use HttpClient in Java 8?

Is there any way to use it in java 8? No, because the jdk. incubator. http module has been added since Java 9.

What is the difference between URLConnection and HttpURLConnection?

URLConnection is the base class. HttpURLConnection is a derived class which you can use when you need the extra API and you are dealing with HTTP or HTTPS only. HttpsURLConnection is a 'more derived' class which you can use when you need the 'more extra' API and you are dealing with HTTPS only.

What is HttpURLConnection used for?

The method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance. The method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.


2 Answers

I would recommend Jakarta Commons HTTP Client over java.net.HttpUrlConnection as it is more mature and has a richer feature set. For example you can ask it to set up multi-threaded connection pool (see MultiThreadedHttpConnectionManager), and it has full support for all the HTTP methods (GET, PUT, POST, DELETE, OPTIONS, TRACE).

like image 155
Jim Ferrans Avatar answered Sep 24 '22 20:09

Jim Ferrans


I'll give you a single, concrete reason to favour Apache's HTTPClient over the JDK implementation: The JDK's HttpUrlConnection doesn't support timeouts*, Apache's HTTPClient does.

Applications should always have the ability to set timeouts when calling into other systems (databases, remote services, your own server backend, ...).

* This was fixed in Java 1.5; Java 1.5 and higher support timeouts in HttpUrlConnection.

like image 40
SteveD Avatar answered Sep 25 '22 20:09

SteveD