Sending HTTP Requests with Apache HttpClient

The following example uses the HTTPExecutorClient class that implements ExecutorClient. Each step is followed by code samples.

To GET Data

This example submits the GET request to the specified URL (urlstr), reads the response, and returns the response to the caller.

/**
 * @param urlstr destination URL (for example
 * https://<HOST>:8443/www/core-service/rest/LoginService/login)
 * @param requestProperties key/value entries to set request headers
 * @return response description of response returned by the server
 * */
public CommandResult sendGet(String urlstr, Map<String, String> requestProperties)
throws IOException {
    HttpClient client = new DefaultHttpClient();
    // 1. Prepare the connection
    HttpGet request = new HttpGet(urlstr);
    // 2. Set optional headers (for example to request data in JSON format)
    for (Map.Entry<String, String> nextParam : requestProperties.entrySet()) {
        request.addHeader(nextParam.getKey(), nextParam.getValue());
    }
    // 3. Submit the request
    HttpResponse response = client.execute(request);
    // 4. Read the response
    String responseStr = "";
    String errMsg = "";
    int responseCode = response.getStatusLine().getStatusCode();
    try {
        if ( HttpStatus.SC_OK != responseCode ) {
            BufferedReader inreader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = inreader.readLine()) != null) {
                  sb.append(line);
            }
            String result = sb.toString();
            inreader.close();
        }
    } catch (IOException e) {
        // Read errMsg from connection.getErrorStream();
        throw e;
    }
    return new CommandResult(responseCode, responseStr, errMsg); }

To POST Data

To POST data, start with the same code as the previous GET example, To GET Data, then replace step 1 with: