114

What is the best Java library to use for HTTP POST, GET etc. in terms of performance, stability, maturity etc.? Is there one particular library that is used more than others?

My requirements are submitting HTTPS POST requests to a remote server. I have used the java.net.* package in the past as well as org.apache.commons.httpclient.* package. Both have got the job done, but I would like some of your opinions/recommendations.

rmcc
  • 3,507
  • 7
  • 29
  • 25

7 Answers7

115

imho: Apache HTTP Client

usage example:

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

public class HttpClientTutorial {

  private static String url = "http://www.apache.org/";

  public static void main(String[] args) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
            new DefaultHttpMethodRetryHandler(3, false));

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
  }
}

some highlight features:

  • Standards based, pure Java, implementation of HTTP versions 1.0 and 1.1
    • Full implementation of all HTTP methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) in an extensible OO framework.
    • Supports encryption with HTTPS (HTTP over SSL) protocol.
    • Granular non-standards configuration and tracking.
    • Transparent connections through HTTP proxies.
    • Tunneled HTTPS connections through HTTP proxies, via the CONNECT method.
    • Transparent connections through SOCKS proxies (version 4 & 5) using native Java socket support.
    • Authentication using Basic, Digest and the encrypting NTLM (NT Lan Manager) methods.
    • Plug-in mechanism for custom authentication methods.
    • Multi-Part form POST for uploading large files.
    • Pluggable secure sockets implementations, making it easier to use third party solutions
    • Connection management support for use in multi-threaded applications. Supports setting the maximum total connections as well as the maximum connections per host. Detects and closes stale connections.
    • Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.
    • Plug-in mechanism for custom cookie policies.
    • Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
    • Response input streams to efficiently read the response body by streaming directly from the socket to the server.
    • Persistent connections using KeepAlive in HTTP/1.0 and persistance in HTTP/1.1
    • Direct access to the response code and headers sent by the server.
    • The ability to set connection timeouts.
    • HttpMethods implement the Command Pattern to allow for parallel requests and efficient re-use of connections.
    • Source code is freely available under the Apache Software License.
Chris
  • 15,429
  • 19
  • 72
  • 74
  • 31
    The documentation is OUT OF DATE though. HttpClient is not a concrete class anymore, it is an interface, therefore the above code WILL NOT WORK as it attempts to instantiate this HttpClient interface. Instead you'll have to instantiate a class that implements HttpClient interface, for example DefaultHttpClient. – therobyouknow Feb 16 '10 at 14:08
  • 5
    it feels like every release is too many major changes...getting really frustrated with this library over the years....and now they seem to leak connections from the pool which I have a max of 20 set up....grrrrrr. – Dean Hiller Oct 22 '12 at 19:16
  • 6
    Apache HttpClient seems to be EOL now, with a new Apache library available. – Andrew Aylett Nov 30 '12 at 17:42
  • 1
    also take a look here guys, excellent answer and maybe enough for some cases: http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests – Chris Oct 26 '13 at 21:32
  • 2
    @Chris best to update the code snippet. – Amriteya Dec 08 '16 at 05:46
  • @Chris and therefore it is no longer applicable and (unless updated), should be downvoted. The link in the answer points to a page that says the project has been discontinued..... – Kröw May 19 '23 at 20:35
27

I would recommend Apache HttpComponents HttpClient, a successor of Commons HttpClient

I would also recommend to take a look at HtmlUnit. HtmlUnit is a "GUI-Less browser for Java programs". http://htmlunit.sourceforge.net/

dbow
  • 637
  • 8
  • 18
Adil
  • 3,248
  • 1
  • 22
  • 27
16

I'm somewhat partial to Jersey. We use 1.10 in all our projects and haven't run into an issue we couldn't solve with it.

Some reasons why I like it:

  • Providers - created soap 1.1/1.2 providers in Jersey and have eliminated the need to use the bulky AXIS for our JAX-WS calls
  • Filters - created database logging filters to log the entire request (including the request/response headers) while preventing logging of sensitive information.
  • JAXB - supports marshaling to/from objects straight from the request/response
  • API is easy to use

In truth, HTTPClient and Jersey are very similar in implementation and API. There is also an extension for Jersey that allows it to support HTTPClient.

Some code samples with Jersey 1.x: https://blogs.oracle.com/enterprisetechtips/entry/consuming_restful_web_services_with

http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/

HTTPClient with Jersey Client: https://blogs.oracle.com/PavelBucek/entry/jersey_client_apache_http_client

ElMattIO
  • 306
  • 2
  • 5
  • I would advice against jersey now, it bring too much dependencies and worst, server side-dependencies that conflict with spring web – Erwan Leroux Apr 08 '21 at 08:16
11

I agree httpclient is something of a standard - but I guess you are looking for options so...

Restlet provides a http client specially designed for interactong with Restful web services.

Example code:

    Client client = new Client(Protocol.HTTP);
    Request r = new Request();
    r.setResourceRef("http://127.0.0.1:8182/sample");
    r.setMethod(Method.GET);
    r.getClientInfo().getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.TEXT_XML));
    client.handle(r).getEntity().write(System.out);

See https://restlet.talend.com/ for more details

Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
Pablojim
  • 8,542
  • 8
  • 45
  • 69
7

I want to mention the Ning Async Http Client Library. I've never used it but my colleague raves about it as compared to the Apache Http Client, which I've always used in the past. I was particularly interested to learn it is based on Netty, the high-performance asynchronous i/o framework, with which I am more familiar and hold in high esteem.

Josh
  • 4,894
  • 6
  • 34
  • 42
6

May I recommend you corn-httpclient. It's simple,fast and enough for most cases.

HttpForm form = new HttpForm(new URI("http://localhost:8080/test/formtest.jsp"));
//Authentication form.setCredentials("user1", "password");
form.putFieldValue("input1", "your value");
HttpResponse response = form.doPost();
assertFalse(response.hasError());
assertNotNull(response.getData());
assertTrue(response.getData().contains("received " + val));

maven dependency

<dependency>
    <groupId>net.sf.corn</groupId>
    <artifactId>corn-httpclient</artifactId>
    <version>1.0.0</version>
</dependency>
Paolo
  • 20,112
  • 21
  • 72
  • 113
Serhat
  • 222
  • 4
  • 2
5

Google HTTP Java Client looks good to me because it can run on Android and App Engine as well.

Umair A.
  • 6,690
  • 20
  • 83
  • 130