April 13, 2010

Jakarta HttpClient , POST request

This library contains a set of very handy utilities for HTTP interaction, in this occasion, I'll show you how to create a POST request:

final String url = "http://localhost:8080/eco/management"
public void sendRequest(Map<String, String> parameters) throws DigestException,   HttpException, IOException {
        println("Sending request to : " + url);
        HttpClient httpClient = new HttpClient();
        PostMethod method = new PostMethod(url);

        for (Entry<String,String> entry : parameters.entrySet()) {
            method.addParameter(entry.getKey(), entry.getValue());
        }
        final int status = httpClient.executeMethod(method);

        if (status == HttpStatus.SC_OK) {
            println("Request successfully processed");
            println("Response : " + new String(method.getResponseBody()));
        }
    }