Example usage for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity

List of usage examples for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity.

Prototype

public StringRequestEntity(String paramString1, String paramString2, String paramString3)
  throws UnsupportedEncodingException

Source Link

Usage

From source file:net.jadler.AbstractJadlerStubbingIntegrationTest.java

@Test
public void havingISOBody() throws Exception {

    onRequest().havingBodyEqualTo(STRING_WITH_DIACRITICS).havingRawBodyEqualTo(ISO_8859_2_REPRESENTATION)
            .respond().withStatus(201);/*from  ww w.  jav  a2  s . c  o m*/

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(
            new StringRequestEntity(STRING_WITH_DIACRITICS, "text/plain", ISO_8859_2_CHARSET.name()));

    int status = client.executeMethod(method);
    assertThat(status, is(201));

    method.releaseConnection();
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.services.SettingsLoaderImpl.java

public void saveConfiguration(RemoteSettings remoteSettings) throws SettingsLoaderException {
    try {//from   w ww  .  java  2  s .c o  m
        logger.debug("Attempting to save Settings for '" + remoteSettings.getSettings().getEid() + "'");
        String xml = xstream.toXML(remoteSettings.getSettings());
        PostMethod method = new PostMethod(remoteSettings.getBasePath()
                + "/hqu/tomcatserverconfig/tomcatserverconfig/saveConfiguration.hqu");
        configureMethod(method, remoteSettings.getSettings().getEid(), remoteSettings.getSessionId(),
                remoteSettings.getCsrfNonce());
        method.setRequestEntity(new StringRequestEntity(xml, "text/xml", "UTF-8"));
        httpClient.executeMethod(method);
        if (method.getStatusCode() >= 300 && method.getStatusCode() < 400) {
            logger.info("Unable to save Settings for '" + remoteSettings.getSettings().getEid()
                    + "', HQ session expired");
            throw new SettingsLoaderException(SESSION_EXPIRED_MESSAGE);
        } else if (method.getStatusCode() >= 400) {
            logger.warn("Unable to save Settings for '" + remoteSettings.getSettings().getEid() + "', "
                    + method.getStatusCode() + " " + method.getStatusText());
            throw new SettingsLoaderException(method.getStatusText());
        }
        remoteSettings.setCsrfNonce(method.getResponseBodyAsString());
        logger.info("Saved Settings for '" + remoteSettings.getSettings().getEid() + "'");
    } catch (SSLHandshakeException e) {
        logger.error("Server SSL certificate is untrusted: " + e.getMessage(), e);
        throw new SettingsLoaderException(
                "Unable to save settings because the server is using an untrusted SSL certificate.  "
                        + "Please check the documentation for more information.",
                e);
    } catch (IOException e) {
        logger.error("Unable to save Settings for '" + remoteSettings.getSettings().getEid() + "': "
                + e.getMessage(), e);
        throw new SettingsLoaderException(
                "Saving settings failed because of a server error, please check the logs for more details", e);
    }
}

From source file:com.cubeia.backoffice.operator.client.OperatorServiceClientHTTP.java

@Override
public void updateConfig(Long operatorId, Map<OperatorConfigParamDTO, String> config) {
    PutMethod method = new PutMethod(String.format(baseUrl + UPDATE_CONFIG, operatorId));
    prepareMethod(method);// w w w .  j  a  v  a  2s . co m
    try {
        String data = serialize(config);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the method.
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:ch.gadp.alfresco.OAuthSSOAuthenticationFilter.java

/**
 * Gets an Alfresco authentication ticket to handle user creation and update
 * @return The new ticket/*from w w  w. j a  v  a  2 s .c  o m*/
 * @throws IOException
 */
protected String getAdminAlfrescoTicket() throws IOException {
    logger.warn("getAdminAlfrescoTicket");
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(getAPIUri(REPOSITORY_API_LOGIN));

    String input = "{ " + "\"username\" : \"" + getConfigurationValue(REPOSITORY_ADMIN_USER) + "\", "
            + "\"password\" : \"" + getConfigurationValue(REPOSITORY_ADMIN_PASSWORD) + "\" " + "}";
    method.setRequestEntity(new StringRequestEntity(input, "application/json", "utf-8"));
    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        return null;
    }

    Gson ticketJSON = new Gson();
    TicketInfo ticket = ticketJSON.fromJson(method.getResponseBodyAsString(), TicketInfo.class);
    return ticket.data.ticket;
}

From source file:com.rometools.propono.atom.client.ClientEntry.java

void addToCollection(final ClientCollection col) throws ProponoException {
    setCollection(col);/*w w w.j a  va  2 s . co m*/
    final EntityEnclosingMethod method = new PostMethod(getCollection().getHrefResolved());
    addAuthentication(method);
    final StringWriter sw = new StringWriter();
    int code = -1;
    try {
        Atom10Generator.serializeEntry(this, sw);
        method.setRequestEntity(new StringRequestEntity(sw.toString(), null, null));
        method.setRequestHeader("Content-type", "application/atom+xml; charset=utf-8");
        getHttpClient().executeMethod(method);
        final InputStream is = method.getResponseBodyAsStream();
        code = method.getStatusCode();
        if (code != 200 && code != 201) {
            throw new ProponoException("ERROR HTTP status=" + code + " : " + Utilities.streamToString(is));
        }
        final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(is),
                getCollection().getHrefResolved(), Locale.US);
        BeanUtils.copyProperties(this, romeEntry);

    } catch (final Exception e) {
        final String msg = "ERROR: saving entry, HTTP code: " + code;
        LOG.debug(msg, e);
        throw new ProponoException(msg, e);
    } finally {
        method.releaseConnection();
    }
    final Header locationHeader = method.getResponseHeader("Location");
    if (locationHeader == null) {
        LOG.warn("WARNING added entry, but no location header returned");
    } else if (getEditURI() == null) {
        final List<Link> links = getOtherLinks();
        final Link link = new Link();
        link.setHref(locationHeader.getValue());
        link.setRel("edit");
        links.add(link);
        setOtherLinks(links);
    }
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private HttpResponse executeMethodJson(EntityEnclosingMethod method, String jsonBody,
        Map<String, String> headers, int timeoutMillis) throws HttpClientException {
    try {//  ww w . j  av a2  s  . c  o m
        setRequestHeaders(headers, method);

        method.setRequestEntity(
                new StringRequestEntity(jsonBody, Constants.APPLICATION_JSON_CONTENT_TYPE, "UTF-8"));
        method.setRequestHeader(Constants.CONTENT_TYPE_HEADER_NAME, Constants.APPLICATION_JSON_CONTENT_TYPE);
        if (timeoutMillis > 0) {
            return executeWithTimeout(method, timeoutMillis);
        } else {
            return execute(method);
        }
    } catch (Exception e) {
        String trimmedMethodBody = (jsonBody.length() > JSON_POST_LOG_LENGTH_LIMIT)
                ? jsonBody.substring(0, JSON_POST_LOG_LENGTH_LIMIT)
                : jsonBody;
        throw new HttpClientException("Error executing " + method.getName() + " request to: "
                + client.getHostConfiguration().getHostURL() + " path: " + method.getPath() + " JSON body: "
                + trimmedMethodBody, e);
    }
}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public void updateAccount(Account account) {
    String resource = String.format(baseUrl + ACCOUNT, account.getId());
    PutMethod method = new PutMethod(resource);
    try {/*from  w ww .j  a  v  a2  s . c o  m*/
        String data = serialize(account);
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));
        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.intuit.tank.http.BaseRequest.java

/**
 * Execute the POST./*from   w ww. j a  v a  2 s.c o  m*/
 */
public void doPost(BaseResponse response) {
    PostMethod httppost = null;
    String theUrl = null;
    try {
        URL url = BaseRequestHandler.buildUrl(protocol, host, port, path, urlVariables);
        theUrl = url.toExternalForm();
        httppost = new PostMethod(url.toString());
        String requestBody = getBody();
        StringRequestEntity entity = new StringRequestEntity(requestBody, getContentType(), contentTypeCharSet);
        httppost.setRequestEntity(entity);

        sendRequest(response, httppost, requestBody);
    } catch (MalformedURLException e) {
        logger.error(LogUtil.getLogMessage("Malformed URL Exception: " + e.toString(), LogEventType.IO), e);
        // swallowing error. validatin will check if there is no response
        // and take appropriate action
        throw new RuntimeException(e);
    } catch (Exception ex) {
        // logger.error(LogUtil.getLogMessage(ex.toString()), ex);
        // swallowing error. validatin will check if there is no response
        // and take appropriate action
        throw new RuntimeException(ex);
    } finally {
        if (null != httppost) {
            httppost.releaseConnection();
        }
        if (APITestHarness.getInstance().getTankConfig().getAgentConfig().getLogPostResponse()) {
            logger.info(LogUtil.getLogMessage("Response from POST to " + theUrl + " got status code "
                    + response.httpCode + " BODY { " + response.response + " }", LogEventType.Informational));
        }
    }

}

From source file:it.geosolutions.figis.requester.HTTPUtils.java

/**
* POSTs a String to the given URL.//from  w ww  .  j a va 2  s  .c o  m
* <BR>Basic auth is used if both username and pw are not null.
*
* @param url The URL where to connect to.
* @param content The content to be sent as a String.
* @param contentType The content-type to advert in the POST.
* @param username Basic auth credential. No basic auth if null.
* @param pw Basic auth credential. No basic auth if null.
* @return The HTTP response as a String if the HTTP response code was 200 (OK).
* @throws MalformedURLException
* @return the HTTP response or <TT>null</TT> on errors.
*/
public static String post(String url, String content, String contentType, String username, String pw) {
    try {
        return post(url, new StringRequestEntity(content, contentType, null), username, pw);
    } catch (UnsupportedEncodingException ex) {
        LOGGER.error("Cannot POST " + url, ex);

        return null;
    }
}

From source file:com.rometools.propono.atom.client.ClientMediaEntry.java

/**
 * Update entry on server.//from   www . j  a  v a 2s. c  om
 */
@Override
public void update() throws ProponoException {
    if (partial) {
        throw new ProponoException("ERROR: attempt to update partial entry");
    }
    EntityEnclosingMethod method = null;
    final Content updateContent = getContents().get(0);
    try {
        if (getMediaLinkURI() != null && getBytes() != null) {
            // existing media entry and new file, so PUT file to edit-media URI
            method = new PutMethod(getMediaLinkURI());
            if (inputStream != null) {
                method.setRequestEntity(new InputStreamRequestEntity(inputStream));
            } else {
                method.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(getBytes())));
            }

            method.setRequestHeader("Content-type", updateContent.getType());
        } else if (getEditURI() != null) {
            // existing media entry and NO new file, so PUT entry to edit URI
            method = new PutMethod(getEditURI());
            final StringWriter sw = new StringWriter();
            Atom10Generator.serializeEntry(this, sw);
            method.setRequestEntity(new StringRequestEntity(sw.toString(), null, null));
            method.setRequestHeader("Content-type", "application/atom+xml; charset=utf8");
        } else {
            throw new ProponoException("ERROR: media entry has no edit URI or media-link URI");
        }
        getCollection().addAuthentication(method);
        method.addRequestHeader("Title", getTitle());
        getCollection().getHttpClient().executeMethod(method);
        if (inputStream != null) {
            inputStream.close();
        }
        final InputStream is = method.getResponseBodyAsStream();
        if (method.getStatusCode() != 200 && method.getStatusCode() != 201) {
            throw new ProponoException(
                    "ERROR HTTP status=" + method.getStatusCode() + " : " + Utilities.streamToString(is));
        }

    } catch (final Exception e) {
        throw new ProponoException("ERROR: saving media entry");
    }
    if (method.getStatusCode() != 201) {
        throw new ProponoException("ERROR HTTP status=" + method.getStatusCode());
    }
}