Example usage for org.apache.http.client.fluent Request bodyString

List of usage examples for org.apache.http.client.fluent Request bodyString

Introduction

In this page you can find the example usage for org.apache.http.client.fluent Request bodyString.

Prototype

public Request bodyString(final String s, final ContentType contentType) 

Source Link

Usage

From source file:eu.trentorise.opendata.jackan.CkanClient.java

/**
 *
 * POSTs a body via HTTP. If {@link CkanResponse#isSuccess()} is false
 * throws {@link CkanException}.//from  w ww .  ja  v a2 s  . c  om
 *
 * @param responseType
 *            a descendant of CkanResponse
 * @param path
 *            something like /api/3/action/package_create
 * @param body
 *            the body of the POST
 * @param contentType
 * @param params
 *            list of key, value parameters. They must be not be url
 *            encoded. i.e. "id","laghi-monitorati-trento"
 * @throws CkanException
 *             on error
 */
private <T extends CkanResponse> T postHttp(Class<T> responseType, String path, String body,
        ContentType contentType, Object... params) {
    checkNotNull(responseType);
    checkNotNull(path);
    checkNotNull(body);
    checkNotNull(contentType);

    String fullUrl = calcFullUrl(path, params);

    T ckanResponse;
    String returnedText;

    try {
        LOG.log(Level.FINE, "Posting to url {0}", fullUrl);
        LOG.log(Level.FINE, "Sending body:{0}", body);
        Request request = Request.Post(fullUrl);

        configureRequest(request);

        Response response = request.bodyString(body, contentType).execute();

        InputStream stream = response.returnResponse().getEntity().getContent();

        try (InputStreamReader reader = new InputStreamReader(stream, Charsets.UTF_8)) {
            returnedText = CharStreams.toString(reader);
        }
    } catch (Exception ex) {
        throw new CkanException("Error while performing a POST! Request url is:" + fullUrl, this, ex);
    }

    try {
        ckanResponse = getObjectMapper().readValue(returnedText, responseType);
    } catch (Exception ex) {
        throw new CkanException(
                "Couldn't interpret json returned by the server! Returned text was: " + returnedText, this, ex);
    }

    if (!ckanResponse.isSuccess()) {
        throwCkanException("Error while performing a POST! Request url is:" + fullUrl, ckanResponse);
    }
    return ckanResponse;

}