Example usage for org.apache.commons.httpclient.methods PostMethod setRequestEntity

List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity

Introduction

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

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:com.cloud.utils.rest.RESTServiceConnector.java

@SuppressWarnings("unchecked")
public <T> T executeCreateObject(final T newObject, final Type returnObjectType, final String uri,
        final Map<String, String> parameters) throws CloudstackRESTException {

    final PostMethod pm = (PostMethod) createMethod(POST_METHOD_TYPE, uri);
    pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
    try {// w ww  .j  a  v  a2s .com
        pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
    } catch (final UnsupportedEncodingException e) {
        throw new CloudstackRESTException("Failed to encode json request body", e);
    }

    executeMethod(pm);

    if (pm.getStatusCode() != HttpStatus.SC_CREATED) {
        final String errorMessage = responseToErrorMessage(pm);
        pm.releaseConnection();
        s_logger.error("Failed to create object : " + errorMessage);
        throw new CloudstackRESTException("Failed to create object : " + errorMessage);
    }

    T result;
    try {
        result = (T) gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
    } catch (final IOException e) {
        throw new CloudstackRESTException("Failed to decode json response body", e);
    } finally {
        pm.releaseConnection();
    }

    return result;
}

From source file:com.legstar.test.cixs.AbstractHttpClientTester.java

/**
 * Perform a request/reply using text/xml as payload.
 * /*from  w  w  w  .  ja v a 2 s .  com*/
 * @param url the target url
 * @param xmlRequest the XML request
 * @param soapAction the soap action
 * @return the XML reply
 * @throws Exception if something goes wrong
 */
public String postXml(final String url, final String xmlRequest, final String soapAction) throws Exception {
    PostMethod postMethod = new PostMethod(url);
    if (soapAction != null && soapAction.length() > 0) {
        postMethod.setRequestHeader("SOAPAction", soapAction);
    }
    StringRequestEntity requestEntity = new StringRequestEntity(xmlRequest, "text/xml", "utf-8");
    postMethod.setRequestEntity(requestEntity);
    int rc = HTTPCLIENT.executeMethod(postMethod);
    String xmlReply = getResponseBodyAsString(postMethod.getResponseBodyAsStream(),
            postMethod.getResponseCharSet());
    postMethod.releaseConnection();
    assertEquals(postMethod.getStatusText() + " " + xmlReply, 200, rc);
    return xmlReply;
}

From source file:com.zb.app.external.wechat.service.WeixinService.java

@SuppressWarnings("deprecation")
public String sendMessage(WeixinMessage weixinMessage) throws Exception {
    StringBuilder sb = new StringBuilder(400);
    sb.append("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=");
    sb.append(getAccessToken());/*from  w  w w.  ja  v a 2s  .c o m*/
    // https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN
    PostMethod method = new PostMethod(sb.toString());
    method.getParams().setContentCharset("utf-8");
    String object2Json = new Gson().toJson(weixinMessage);
    logger.error(object2Json);
    // method.addParameter("body", object2Json);
    // method.setRequestBody(object2Json);
    RequestEntity entity = new StringRequestEntity(object2Json);
    method.setRequestEntity(entity);
    String result = HttpClientUtils.getResponseBodyAsString(method);
    logger.error(result);
    return result;
}

From source file:de.mpg.escidoc.services.edoc.PubManImport.java

private String assignVersionPid(String id, String lastModificationDate) throws Exception {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(CORESERVICES_URL + "/ir/item/" + id + "/assign-version-pid");
    postMethod.addRequestHeader("Cookie", "escidocCookie=" + userHandle);
    String body = "<param last-modification-date=\"" + lastModificationDate
            + "\"><url>http://qa-pubman.mpdl.mpg.de:8080/faces/item/" + id + "</url></param>";

    postMethod.setRequestEntity(new StringRequestEntity(body));
    ProxyHelper.executeMethod(httpClient, postMethod);

    String response = postMethod.getResponseBodyAsString();

    if (postMethod.getStatusCode() != 200) {
        throw new RuntimeException(response);
    }/*from   w w w.j  ava  2s  . c o m*/

    return response;
}

From source file:com.bakhtiyor.android.tumblr.TumblrService.java

private void uploadPhoto(String email, String password, String caption, boolean isPrivate, String filename) {
    try {//w  w  w .j  a v a 2 s  .  c o m
        File file = new File(filename);
        final HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
        final PostMethod multipartPost = new PostMethod(API_URL);
        Part[] parts = { new StringPart(FIELD_EMAIL, email), new StringPart(FIELD_PASSWORD, password),
                new StringPart(FIELD_TYPE, "photo"), new StringPart("generator", GENERATOR),
                new StringPart(FIELD_CAPTION, caption), new StringPart(FIELD_PRIVATE, isPrivate ? "1" : "0"),
                new FilePart("data", file) };
        multipartPost.setRequestEntity(new MultipartRequestEntity(parts, multipartPost.getParams()));
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        int id = new Random().nextInt();
        showUploadingNotification(id);
        int status = httpClient.executeMethod(multipartPost);
        clearNotification(id);
        if (status == 201) {
            showResultNotification("Successful Uploaded");
        } else {
            showResultNotification("Error occured");
        }
    } catch (Throwable e) {
        Log.e(TAG, e.getMessage(), e);
    }
}

From source file:eu.learnpad.core.impl.mt.XwikiBridgeInterfaceRestResource.java

@Override
public InputStream transform(ModelSetType type, InputStream model) throws LpRestException {
    HttpClient httpClient = this.getAnonymousClient();
    String uri = String.format("%s/learnpad/mt/bridge/transform", this.restPrefix);
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM);
    postMethod.addRequestHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM);
    NameValuePair[] queryString = new NameValuePair[1];
    queryString[0] = new NameValuePair("type", type.toString());
    postMethod.setQueryString(queryString);

    RequestEntity modelEntity = new InputStreamRequestEntity(model);
    postMethod.setRequestEntity(modelEntity);
    try {/*w w w.j  ava 2s .  c  o m*/
        httpClient.executeMethod(postMethod);
    } catch (IOException e) {
        String message = String.format("Error in sending POST to Model Transformer component [type: %s]", type);
        throw new LpRestExceptionXWikiImpl(message, e);
    }
    try {
        return postMethod.getResponseBodyAsStream();
    } catch (IOException e) {
        String message = String.format(
                "Model Transformer component failed to return result of transformation [type: %s]", type);
        throw new LpRestExceptionXWikiImpl(message, e);
    }
}

From source file:com.cloud.network.bigswitch.BigSwitchBcfApi.java

protected <T> String executeCreateObject(final T newObject, final String uri,
        final Map<String, String> parameters) throws BigSwitchBcfApiException {
    checkInvariants();//  w w w  .  j a  va 2  s .c  o  m

    PostMethod pm = (PostMethod) createMethod("post", uri, _port);

    setHttpHeader(pm);

    try {
        pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), CONTENT_JSON, null));
    } catch (UnsupportedEncodingException e) {
        throw new BigSwitchBcfApiException("Failed to encode json request body", e);
    }

    executeMethod(pm);

    String hash = checkResponse(pm, "BigSwitch HTTP create failed: ");

    pm.releaseConnection();

    return hash;
}

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

public void saveConfiguration(RemoteSettings remoteSettings) throws SettingsLoaderException {
    try {/*www .  ja  va2  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:cz.muni.fi.pa165.creatures.rest.client.services.impl.RegionCRUDServiceImpl.java

@Override
public void create(RegionDTO dto) {
    PostMethod postMethod = new PostMethod(uri);
    StringWriter writer = new StringWriter();

    try {//from w w  w .  j  a  v  a2  s.  c o  m
        context.createMarshaller().marshal(regionMapping.DTOtoEntity(dto), writer);
    } catch (JAXBException ex) {
        logger.log(Level.INFO, "Unable to marshall RegionDTO {0}", dto);
        return;
    }

    RequestEntity entity = new InputStreamRequestEntity(new ByteArrayInputStream(writer.toString().getBytes()));
    postMethod.setRequestEntity(entity);
    CRUDServiceHelper.send(postMethod);
}

From source file:cz.muni.fi.pa165.creatures.rest.client.services.impl.WeaponCRUDServiceImpl.java

@Override
public void create(WeaponDTO dto) {
    PostMethod postMethod = new PostMethod(uri);
    StringWriter writer = new StringWriter();

    try {/* w  w w  .j  a v a  2  s  .  com*/
        context.createMarshaller().marshal(weaponMapping.DTOtoEntity(dto), writer);
    } catch (JAXBException ex) {
        logger.log(Level.INFO, "Unable to marshall CreatureDTO {0}", dto);
        return;
    }

    RequestEntity entity = new InputStreamRequestEntity(new ByteArrayInputStream(writer.toString().getBytes()));
    postMethod.setRequestEntity(entity);
    CRUDServiceHelper.send(postMethod);
}