Apache Commons Httpclient



  1. C# Httpclient
  1. I think the httpclient library doesn't include the mime parts, those are in httpmime. This is a transitive dependency of httpclient, but as that is ignored, it won't be taken into account. Try adding this dependency: compile 'org.apache.httpcomponents:httpmime:4.2.3'.
  2. How to make Apache Commons HttpClient 3.1 ignore HTTPS certificate invalidity? See more linked questions. How to get.pem file from.key and.crt files? Trusting all certificates using HttpClient over HTTPS. SSL certificate rejected trying to access GitHub over HTTPS behind firewall.
Commons

I do appreciate the versatility offered by REST-style web services when designing clients, and that’s precisely what I will be discussing in this series of posts. There is a lot to be said about a web-service approach such as REST where the client can use pretty much any HTTP-based API to retrieve/update/delete data. I will take you through the steps of defining a server-side Java class, use REST annotations to turn it into a web service and show you four ways to access such a service: Through the Apache Commons HTTP API, through the native J2SE API, through the JAX-WS API and finally through the Spring REST Client API.
This post is the first one of a mini-series:

Apache Commons Httpclient
Clients Like REST part 1Apache HTTP Commons Client
Clients Like REST part 2Native J2SE API Client
Clients Like REST part 3JAX-WS client API

Name Email Dev Id Roles Organization; Ortwin Glueck: oglueck -at- apache.org: oglueck: Emeritus PMC: Oleg Kalnichevski: olegk -at- apache.org: olegk: Committer, PMC.

A few things to note:

  1. This is not about the proper design of the server-side code, I will probably devote another blog to explore best-practices in this area and comment on the use/misuse of Annotations
  2. This is not about the best protocol for data transport, again I could probably compare the merits of various data protocols for various cases/load usage/performance requirements in another blog
  3. This is about setting up four different (Java) clients to perform similar operations on the data using four different APIs, you are left to judge which one fits best your particular project
  4. The first part will illustrate a client using Apache Commons HttpClient, part 2 will illustrate a client simply using the J2SE API

Before proceeding let’s just say that in general I am not a huge fan of RESTful services. More precisely my issue with REST is the way organizations tend to implement REST services, not necessarily because of disagreements with the REST philosophy as described in Roy Fielding dissertation (I really like chapter five). All too often REST is used as a lame excuse to expose some poorly designed functionality using XML-over-HTTP and pompously calling that “web services”. Of course, I cannot help but note that many recent developments in REST try to precisely bridge the gap with SOAP, such as the usage of WSDL 2.0 to accommodate contracts (see the good introduction at http://www.w3.org/TR/2007/REC-wsdl20-primer-20070626/)

Now back to the main point of this post: I will take you through the implementation of a simple car statistics web service which allows the client to invoke five operations: Get all basic statistics (top speed in mph, 0 to 60 time, 1/4 mile time and 60 to 0 stopping distance), get statistics for a particular car, add statistics for a new car, update the statistics of an existing car and delete a particular statistics. Hopefully this example will prove sufficiently sufficiently universal.

We’ll start by defining the server-side classes; as mentioned previously I will devote another blog to explore best-practices in this area, for now let’s just concentrate on the class definitions. First let’s define the main service interface describing the five operations and note that nothing in the code pertains to web services:

Here is the definition of the AutoStatistics entity class, just note the presence of the @XmlRootElement(name=”AutoStatistics”) annotation. Capture 20. Since we’ll be using JAXB 2 in the background, the @XmlRootElement annotation in this context refers to both an XML Schema Type and a Global Element Definition of that type and the name attribute is the name of the Global Element Definition. By contrast a property or attribute of a class would be tagged with the @XmlElement annotation to indicate a Schema Element Definition. We are omitting here the namespace attribute in @XmlRootElement. Finally do note that I choose to override equals() and hashCode(), the reason will become obvious when we get at the client code towards the end of the post.

And here is the definition of the AllAutoStatistics entity class, note here that it provides a static snapshot of the Collection of AutoStatistics objects:

And here is the heart of the server-side code, the implementation of the IAutoStatService interface. A couple of points: The class is annotated with @Produces( { “application/json”, “application/xml” } ) which defines the media type(s) that the methods of a AutoStatServiceImpl can produce and with @Path( “/AutoStatService” ) which identifies the URI path that AutoStatServiceImpl will serve requests for.

Mac lethal irish goodbye download. Once you have compiled and deployed your code (I used CXF 2.2) we can turn, at last, to the client. This post is about writing clients for RESTful services and I have chosen to start with the Apache Commons HttpClient because

  1. It is a fairly popular/stable HTTP API wrapper
  2. There is nothing in this API that is REST-specific or even Web Services-specific; this point is worth stressing, by properly setting up the @javax.ws.rs.Path annotation on the server class the client will be able to call the addAutoStatistics() operation, for example, simply by constructing a POST request in the form http://<host&gt;:<port>/autoStats/AutoStatService/add
  3. It throws intelligent (read human readable) exceptions when an HTTP operation fails

You will note that the client code is wrapped in JUnit test cases; that’s because I want to explicitly show the success/failure of the operations. I also want to demonstrate the statelessness of the various operations, so setUp() and tearDown() come in handy. Now the unit testing framework in itself is quite irrelevant to this exercise but if you are just getting started with your client code then setting up test cases is indeed a good idea.

The next installment will show you how to write a client using just the J2SE API.

Execute the Method

Apache commons httpclient timeout

The actual execution of the method is performed by calling executeMethod on the client and passing in the method to execute. Since networks connections are unreliable, we also need to deal with any errors that occur.

Download itunes for mac big sur. There are two kinds of exceptions that could be thrown by executeMethod, HttpException and IOException.

The other useful piece of information is the status code that is returned by the server. This code is returned by executeMethod as an int and can be used to determine if the request was successful or not and can sometimes indicate that further action is required by the client such as providing authentication credentials.

HttpException

An HttpException represents a logical error and is thrown when the request cannot be sent or the response cannot be processed due to a fatal violation of the HTTP specification. Usually this kind of exceptions cannot be recovered from. For a detailed discussion on protocol exceptions please refer to the HttpClient exception handling guide. Note that HttpException actually extends IOException so you can just ignore it and catch the IOException if your application does not distinguish between protocol and transport errors.

IOException

A plain IOException (which is not a subclass of HttpException) represents a transport error and is thrown when an error occurs that is likely to be a once-off I/O problem. Usually the request has a good chance of succeeding on a second attempt, so per default HttpClient will try to recover the request automatically. For a detailed discussion on transport exceptions please refer to the HttpClient exception handling guide.

Method recovery

Apache commons httpclient apiApache

Per default HttpClient will automatically attempt to recover from the not-fatal errors, that is, when a plain IOException is thrown. HttpClient will retry the method three times provided that the request has never been fully transmitted to the target server. For a detailed discussion on HTTP method recovery please refer to the HttpClient exception handling guide

Default recovery procedure can be replaced with a custom one. The number of automatic retries can be increased. HttpClient can also be instructed to retry the method even though the request may have already been processed by the server and the I/O exception has occurred while receiving the response. Please exercise caution when enabling auto-retrial. Use it only if the method is known to be idempotent, that is, it is known to be safe to retry multiple times without causing data corruption or data inconsistency.

C# Httpclient

The rule of thumb is GET methods are usually safe unless known otherwise, entity enclosing methods such as POST and PUT are usually unsafe unless known otherwise.