The Bad Programmer

POST with Apache HttpClient 4



I recently started using Apache’s HttpClient 4, I was previously using version 3 and I discovered there is a vast difference in the APIs between the two versions. None of the documentation I found for HttpClient 4 had a full example of using POST with connection and socket timeout set. From the documentation I did find and the JavaDoc I pieced together this full example. For this code I used httpclient-4.3.2.jar which also needed httpcore-4.3.1.jar. I use IVY for dependency management and this entry in ivy.xml got me what I needed:

<dependency org="org.apache.httpcomponents" name="httpclient" rev="4.3.2"/>

Take a look at the Javadoc for RequestConfig.Builder for what other options are available.

If you need to convert the InputStream from the response to a String I have a quick how-to for that.

 public void executePost(String destinationUrl, Map pairs) {
        //Set any needed config options, here is how you would set connection and socket timeout
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        //Timeout for getting a connection to the web server
        configBuilder.setConnectTimeout(2000); 
        //Timeout for data from web server once a connection is established
        configBuilder.setSocketTimeout(2000);  
        //Create a List of BasicNameValuePairs, here I am doing it from a Map that was passed in. Do whatever
        //it is you need to do
        List nameValuePairs = new ArrayList(pairs.size());
        for (Map.Entry entry : pairs.entrySet()) {
            nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        //Create an HttpPost and set your config builder here if you have any custom settings
        HttpPost post = new HttpPost(destinationUrl);
        post.setConfig(configBuilder.build());
        try {
            //Create an encoded form entity and assign it to the HttpPost object
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, Consts.UTF_8);
            post.setEntity(entity);
            //Execute the post, this returns an HttpResponse if all is well or throws an exception if one of the
            //timeout values are met
            HttpResponse httpResponse = this.localHttpClient.get().execute(post);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode >= 200 && statusCode <= 299) 
                //2xx is success, handle them as success. Or handle specific status codes, whatever the case
                //may be
                InputStream responseStream = httpResponse.getEntity().getContent();
                //Do something with the responseStream, convert it to a String, pass it to an XML parser, whatever
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            post.releaseConnection();
        }
    }