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:com.cubeia.backoffice.operator.client.OperatorServiceClientHTTP.java

@Override
public void updateOperator(OperatorDTO operator) {
    PutMethod method = new PutMethod(baseUrl + UPDATE_OPERATOR);
    prepareMethod(method);// ww w  . j  a  v a 2  s. c o m
    try {

        String data = serialize(operator);
        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:net.jadler.AbstractJadlerStubbingIntegrationTest.java

@Test
public void havingUTF8Body() throws Exception {

    onRequest().havingBodyEqualTo(STRING_WITH_DIACRITICS).havingRawBodyEqualTo(UTF_8_REPRESENTATION).respond()
            .withStatus(201);//from w ww.j a  v  a 2  s . com

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

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

    method.releaseConnection();
}

From source file:com.cerema.cloud2.lib.resources.shares.UpdateRemoteShareOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    int status = -1;

    /// prepare array of parameters to update
    List<Pair<String, String>> parametersToUpdate = new ArrayList<Pair<String, String>>();
    if (mPassword != null) {
        parametersToUpdate.add(new Pair<String, String>(PARAM_PASSWORD, mPassword));
    }/*from   w w w . jav  a  2s . c om*/
    if (mExpirationDateInMillis < 0) {
        // clear expiration date
        parametersToUpdate.add(new Pair(PARAM_EXPIRATION_DATE, ""));

    } else if (mExpirationDateInMillis > 0) {
        // set expiration date
        DateFormat dateFormat = new SimpleDateFormat(FORMAT_EXPIRATION_DATE);
        Calendar expirationDate = Calendar.getInstance();
        expirationDate.setTimeInMillis(mExpirationDateInMillis);
        String formattedExpirationDate = dateFormat.format(expirationDate.getTime());
        parametersToUpdate.add(new Pair(PARAM_EXPIRATION_DATE, formattedExpirationDate));

    } // else, ignore - no update
    if (mPermissions > 0) {
        // set permissions
        parametersToUpdate.add(new Pair(PARAM_PERMISSIONS, Integer.toString(mPermissions)));
    }

    if (mPublicUpload != null) {
        parametersToUpdate.add(new Pair(PARAM_PUBLIC_UPLOAD, Boolean.toString(mPublicUpload)));
    }

    /// perform required PUT requests
    PutMethod put = null;
    String uriString = null;

    try {
        Uri requestUri = client.getBaseUri();
        Uri.Builder uriBuilder = requestUri.buildUpon();
        uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH.substring(1));
        uriBuilder.appendEncodedPath(Long.toString(mRemoteId));
        uriString = uriBuilder.build().toString();

        for (Pair<String, String> parameter : parametersToUpdate) {
            if (put != null) {
                put.releaseConnection();
            }
            put = new PutMethod(uriString);
            put.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
            put.setRequestEntity(new StringRequestEntity(parameter.first + "=" + parameter.second,
                    ENTITY_CONTENT_TYPE, ENTITY_CHARSET));

            status = client.executeMethod(put);

            if (status == HttpStatus.SC_OK) {
                String response = put.getResponseBodyAsString();

                // Parse xml response
                ShareToRemoteOperationResultParser parser = new ShareToRemoteOperationResultParser(
                        new ShareXMLParser());
                parser.setOwnCloudVersion(client.getOwnCloudVersion());
                parser.setServerBaseUri(client.getBaseUri());
                result = parser.parse(response);

            } else {
                result = new RemoteOperationResult(false, status, put.getResponseHeaders());
            }
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Exception while updating remote share ", e);
        if (put != null) {
            put.releaseConnection();
        }

    } finally {
        if (put != null) {
            put.releaseConnection();
        }
    }
    return result;
}

From source file:it.geosolutions.geonetwork.util.HTTPUtils.java

/**
 * PUTs a String to the given URL./* w  w  w . j a  va  2s.  co  m*/
 *
 * @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 PUT.
 * @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 String put(String url, String content, String contentType) {
    try {
        return put(url, new StringRequestEntity(content, contentType, null));
    } catch (UnsupportedEncodingException ex) {
        LOGGER.error("Cannot PUT " + url, ex);
        return null;
    }
}

From source file:com.nextcloud.android.sso.InputStreamBinder.java

private InputStream processRequest(final NextcloudRequest request) throws UnsupportedOperationException,
        com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException,
        OperationCanceledException, AuthenticatorException, IOException {
    Account account = AccountUtils.getOwnCloudAccountByName(context, request.getAccountName()); // TODO handle case that account is not found!
    if (account == null) {
        throw new IllegalStateException(EXCEPTION_ACCOUNT_NOT_FOUND);
    }//from  w w w .  j a v  a  2 s . c o  m

    // Validate token
    if (!isValid(request)) {
        throw new IllegalStateException(EXCEPTION_INVALID_TOKEN);
    }

    // Validate URL
    if (request.getUrl().length() == 0 || request.getUrl().charAt(0) != PATH_SEPARATOR) {
        throw new IllegalStateException(EXCEPTION_INVALID_REQUEST_URL,
                new IllegalStateException("URL need to start with a /"));
    }

    OwnCloudClientManager ownCloudClientManager = OwnCloudClientManagerFactory.getDefaultSingleton();
    OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
    OwnCloudClient client = ownCloudClientManager.getClientFor(ocAccount, context);

    String requestUrl = client.getBaseUri() + request.getUrl();
    HttpMethodBase method;

    switch (request.getMethod()) {
    case "GET":
        method = new GetMethod(requestUrl);
        break;

    case "POST":
        method = new PostMethod(requestUrl);
        if (request.getRequestBody() != null) {
            StringRequestEntity requestEntity = new StringRequestEntity(request.getRequestBody(),
                    CONTENT_TYPE_APPLICATION_JSON, CHARSET_UTF8);
            ((PostMethod) method).setRequestEntity(requestEntity);
        }
        break;

    case "PUT":
        method = new PutMethod(requestUrl);
        if (request.getRequestBody() != null) {
            StringRequestEntity requestEntity = new StringRequestEntity(request.getRequestBody(),
                    CONTENT_TYPE_APPLICATION_JSON, CHARSET_UTF8);
            ((PutMethod) method).setRequestEntity(requestEntity);
        }
        break;

    case "DELETE":
        method = new DeleteMethod(requestUrl);
        break;

    default:
        throw new UnsupportedOperationException(EXCEPTION_UNSUPPORTED_METHOD);

    }

    method.setQueryString(convertMapToNVP(request.getParameter()));
    method.addRequestHeader("OCS-APIREQUEST", "true");

    client.setFollowRedirects(request.isFollowRedirects());
    int status = client.executeMethod(method);

    // Check if status code is 2xx --> https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success
    if (status >= HTTP_STATUS_CODE_OK && status < HTTP_STATUS_CODE_MULTIPLE_CHOICES) {
        return method.getResponseBodyAsStream();
    } else {
        throw new IllegalStateException(EXCEPTION_HTTP_REQUEST_FAILED,
                new IllegalStateException(String.valueOf(status)));
    }
}

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

@Override
public String addProcessInstance(ProcessInstanceData data) throws LpRestException {
    HttpClient httpClient = this.getAnonymousClient();
    String uri = String.format("%s/learnpad/sim/bridge/instances", this.restPrefix);

    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader("Content-Type", "application/json");

    try {//from   w  w w  . j ava2s .  c  o  m
        // Not fully tested, but is looks working for our purposes -- Gulyx
        String mashelledData = objectWriter.writeValueAsString(data);

        RequestEntity requestEntity = new StringRequestEntity(mashelledData, "application/json", "UTF-8");
        postMethod.setRequestEntity(requestEntity);

        httpClient.executeMethod(postMethod);

        // Not fully tested, but is looks working for our purposes -- Gulyx
        return objectReaderString.readValue(postMethod.getResponseBodyAsStream());
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

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

protected <T> void executeUpdateObject(T newObject, String uri, Map<String, String> parameters)
        throws BigSwitchVnsApiException {
    if (_host == null || _host.isEmpty()) {
        throw new BigSwitchVnsApiException("Hostname is null or empty");
    }/*from   w  ww.  j  av  a2  s .  c o m*/

    Gson gson = new Gson();

    PutMethod pm = (PutMethod) createMethod("put", uri, 80);
    pm.setRequestHeader(CONTENT_TYPE, CONTENT_JSON);
    pm.setRequestHeader(ACCEPT, CONTENT_JSON);
    pm.setRequestHeader(HTTP_HEADER_INSTANCE_ID, CLOUDSTACK_INSTANCE_ID);
    try {
        pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), CONTENT_JSON, null));
    } catch (UnsupportedEncodingException e) {
        throw new BigSwitchVnsApiException("Failed to encode json request body", e);
    }

    executeMethod(pm);

    if (pm.getStatusCode() != HttpStatus.SC_OK) {
        String errorMessage = responseToErrorMessage(pm);
        pm.releaseConnection();
        s_logger.error("Failed to update object : " + errorMessage);
        throw new BigSwitchVnsApiException("Failed to update object : " + errorMessage);
    }
    pm.releaseConnection();
}

From source file:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java

private static void freeCgiAsyncResources(String endpoint, EndpointReference epr) throws MobyException {
    // construct the Httpclient
    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "jMoby/Taverna2");
    // create the post method
    PostMethod method = new PostMethod(endpoint + "/destroy");

    // put our data in the request
    RequestEntity entity;/*from  w  w w. j av  a  2s .  c  o m*/
    try {
        entity = new StringRequestEntity("<Destroy xmlns=\"http://docs.oasis-open.org/wsrf/rl-2\"/>",
                "text/xml", null);
    } catch (UnsupportedEncodingException e) {
        throw new MobyException("Problem posting data to webservice", e);
    }
    method.setRequestEntity(entity);

    // set the header
    StringBuffer httpheader = new StringBuffer();
    httpheader.append("<moby-wsrf>");
    httpheader.append("<wsa:Action xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">"
            + DESTROY_RESOURCE_ACTION + "</wsa:Action>");
    httpheader.append(
            "<wsa:To xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsu:Id=\"To\">"
                    + endpoint + "</wsa:To>");
    httpheader.append(
            "<mobyws:ServiceInvocationId xmlns:mobyws=\"http://biomoby.org/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsa:IsReferenceParameter=\"true\">"
                    + epr.getServiceInvocationId() + "</mobyws:ServiceInvocationId>");
    httpheader.append("</moby-wsrf>");
    method.addRequestHeader("moby-wsrf", httpheader.toString().replaceAll("\r\n", ""));
    // retry up to 10 times
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(10, true));

    // call the method
    try {
        int result = client.executeMethod(method);
        if (result != HttpStatus.SC_OK)
            throw new MobyException(
                    "Async HTTP POST service returned code: " + result + "\n" + method.getStatusLine());
    } catch (IOException e) {
        throw new MobyException("Problem reading response from webservice", e);
    } finally {
        // Release current connection to the connection pool once you are
        // done
        method.releaseConnection();
    }
}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

public static void populateCSE(String authtoken, String domain, double score) {

    try {//from   w  w w.  j a  v a2  s .c  om
        HttpClient client = new HttpClient();
        PostMethod annotation_post = new PostMethod("http://www.google.com/coop/api/default/annotations/");

        String label;
        domain = URLEncoder.encode(domain, "UTF-8");
        if (domain.indexOf("http") < 0)
            label = "<Annotation about=\"http://" + domain + "/*\" score=\"" + score + "\">";
        else
            label = "<Annotation about=\"" + domain + "/*\" score=\"" + score + "\">";
        String new_annotation = "<Batch>" + "<Add>" + "<Annotations>" + label
                + "<Label name=\"_cse_testengine\"/>" + "</Annotation>" + "</Annotations>" + "</Add>"
                + "</Batch>";

        System.out.println("uploading annotation :" + new_annotation);
        annotation_post.addRequestHeader("Content-type", "text/xml");
        annotation_post.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken);

        StringRequestEntity rq_en = new StringRequestEntity(new_annotation, "text/xml", "UTF-8");
        annotation_post.setRequestEntity(rq_en);

        int astatusCode = client.executeMethod(annotation_post);

        if (astatusCode == HttpStatus.SC_OK) {
            System.out.println("Annotations updated");
            //indexurlcount++;
        } else {
            System.out.println("Annotation update failed");
            String responseBody = IOUtils.toString(annotation_post.getResponseBodyAsStream(), "UTF-8");
            System.out.println("Result remoteRequest: " + responseBody);
            System.out.println("Annotation update failed");
            //rejectedurlcount++;
        }
    } catch (Exception e) {
        System.out.println("\nexception:" + e.getMessage());
    }
}

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

public <T> void executeUpdateObject(final T newObject, final String uri, final Map<String, String> parameters)
        throws CloudstackRESTException {

    final PutMethod pm = (PutMethod) createMethod(PUT_METHOD_TYPE, uri);
    pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
    try {/*ww  w. j  a  va  2 s.c o m*/
        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_OK) {
        final String errorMessage = responseToErrorMessage(pm);
        pm.releaseConnection();
        s_logger.error("Failed to update object : " + errorMessage);
        throw new CloudstackRESTException("Failed to update object : " + errorMessage);
    }
    pm.releaseConnection();
}