Example usage for org.apache.commons.httpclient.methods DeleteMethod getResponseBodyAsString

List of usage examples for org.apache.commons.httpclient.methods DeleteMethod getResponseBodyAsString

Introduction

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

Prototype

@Override
public String getResponseBodyAsString() throws IOException 

Source Link

Document

Returns the response body of the HTTP method, if any, as a String .

Usage

From source file:demo.jaxrs.search.client.Client.java

private static void delete(final String url, final HttpClient httpClient) throws IOException, HttpException {

    System.out.println("Sent HTTP DELETE request to remove all books from catalog");

    final DeleteMethod delete = new DeleteMethod(url);
    try {//ww w .j  a  v a2s . c o m
        int status = httpClient.executeMethod(delete);
        if (status == 200) {
            System.out.println(delete.getResponseBodyAsString());
        }
    } finally {
        delete.releaseConnection();
    }
}

From source file:com.linkedin.pinot.common.utils.SchemaUtils.java

/**
 * Given host, port and schema name, send a http DELETE request to delete the {@link Schema}.
 *
 * @return <code>true</code> on success.
 * <P><code>false</code> on failure.
 *//*  w w  w.  j a  v a  2 s  . c  o m*/
public static boolean deleteSchema(@Nonnull String host, int port, @Nonnull String schemaName) {
    Preconditions.checkNotNull(host);
    Preconditions.checkNotNull(schemaName);

    try {
        URL url = new URL("http", host, port, "/schemas/" + schemaName);
        DeleteMethod httpDelete = new DeleteMethod(url.toString());
        try {
            int responseCode = HTTP_CLIENT.executeMethod(httpDelete);
            if (responseCode >= 400) {
                String response = httpDelete.getResponseBodyAsString();
                LOGGER.warn("Got error response code: {}, response: {}", responseCode, response);
                return false;
            }
            return true;
        } finally {
            httpDelete.releaseConnection();
        }
    } catch (Exception e) {
        LOGGER.error("Caught exception while getting the schema: {} from host: {}, port: {}", schemaName, host,
                port, e);
        return false;
    }
}

From source file:com.buglabs.dragonfly.util.WSHelper.java

protected static String delete(String url) throws HttpException, IOException {
    HttpClient c = new HttpClient();
    DeleteMethod delete = new DeleteMethod(url);
    int response = c.executeMethod(delete);

    if (response >= 400)
        throw new HttpException("Unable to complete delete operation with HTTP error code " + response + ".");

    return delete.getResponseBodyAsString();
}

From source file:com.owncloud.android.lib.resources.notifications.UnregisterAccountDeviceForNotificationsOperation.java

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

    try {//  w ww. j a v a  2 s. c o m
        // Post Method
        delete = new DeleteMethod(client.getBaseUri() + OCS_ROUTE);

        delete.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);

        status = client.executeMethod(delete);
        String response = delete.getResponseBodyAsString();

        if (isSuccess(status)) {
            result = new RemoteOperationResult(true, status, delete.getResponseHeaders());
            Log_OC.d(TAG, "Successful response: " + response);
        } else {
            result = new RemoteOperationResult(false, status, delete.getResponseHeaders());
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Exception while registering device for notifications", e);

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

From source file:javaapplicationclientrest.ControllerCliente.java

public void removerNoticia(String id) {

    DeleteMethod del = new DeleteMethod(String.format(Constants.REMOVE_NOTICIA, id));
    //        System.out.println(String.format(Constants.REMOVE_NOTICIA, id));
    try {//from w  ww  .  j a  v a 2 s  .  c  o m
        http.executeMethod(del);
        System.out.println("Status: " + del.getStatusText());
        System.out.println(del.getResponseBodyAsString());

    } catch (IOException ex) {

        Logger.getLogger(ControllerCliente.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.funambol.json.dao.JsonDAOImpl.java

public JsonResponse removeItem(String token, String id, long since) throws HttpException, IOException {

    String request = Utility.getUrl(jsonServerUrl, resourceType, REMOVE_ITEM_URL) + Utility.URL_SEP + id;

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: start removeItem with id:" + id + "and since=" + since);
    }//from   ww w .  ja v  a2  s  .  co  m

    DeleteMethod remove = new DeleteMethod(request);

    if (since != 0) {
        NameValuePair nvp_since = new NameValuePair();
        nvp_since.setName("since");
        nvp_since.setValue("" + since);
        NameValuePair[] nvp = { nvp_since };
        remove.setQueryString(nvp);
    }

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: removeItem request:" + request);
    }
    remove.setRequestHeader(Utility.TOKEN_HEADER_NAME, token);

    int statusCode = 0;
    String responseBody = null;
    try {
        statusCode = httpClient.executeMethod(remove);
        responseBody = remove.getResponseBodyAsString();
    } finally {
        remove.releaseConnection();
    }

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: deleteItem response " + responseBody);
        log.trace("JsonDAOImpl: item with id:" + id + " removed");
    }

    JsonResponse response = new JsonResponse(statusCode, responseBody);

    return response;
}

From source file:com.funambol.json.dao.JsonDAOImpl.java

public JsonResponse removeAllItems(String token, long since) throws HttpException, IOException {

    String request = Utility.getUrl(jsonServerUrl, resourceType, REMOVE_ITEM_URL);

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: start removeAllItems");
    }//w w  w  . j  a va2 s  . c  om

    DeleteMethod remove = new DeleteMethod(request);

    if (since != 0) {
        NameValuePair nvp_since = new NameValuePair();
        nvp_since.setName("since");
        nvp_since.setValue("" + since);
        NameValuePair[] nvp = { nvp_since };
        remove.setQueryString(nvp);
    }

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: removeAllItem request:" + request);
    }
    remove.setRequestHeader(Utility.TOKEN_HEADER_NAME, token);

    int statusCode = 0;
    String responseBody = null;
    try {
        statusCode = httpClient.executeMethod(remove);
        responseBody = remove.getResponseBodyAsString();
    } finally {
        remove.releaseConnection();
    }

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: deleteAllItem response " + responseBody);
    }

    JsonResponse response = new JsonResponse(statusCode, responseBody);

    return response;
}

From source file:com.funambol.json.api.dao.FunambolJSONApiDAO.java

protected String sendDeleteRequest(String REQUEST, long since, long until) throws IOOperationException {

    String response = null;/*from www.  j a  va  2s .c  o m*/
    DeleteMethod method = null;
    try {

        HttpClient httpClient = new HttpClient();

        method = new DeleteMethod(REQUEST);

        addSinceUntil(method, since, until);

        if (log.isTraceEnabled()) {
            log.trace("\nREQUEST: " + REQUEST + "");
        }
        if (this.sessionid != null) {
            method.setRequestHeader("Authorization", this.sessionid);
        }

        printHeaderFields(method.getRequestHeaders(), "REQUEST");

        int code = httpClient.executeMethod(method);

        response = method.getResponseBodyAsString();

        if (log.isTraceEnabled()) {
            log.trace("RESPONSE code: " + code);
        }
        printHeaderFields(method.getResponseHeaders(), "RESPONSE");

    } catch (Exception e) {
        throw new IOOperationException("Error GET Request ", e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }

    return response;
}

From source file:com.worldline.easycukes.rest.client.RestService.java

/**
 * Allows to send a DELETE request, with parameters using JSON format
 *
 * @param path path to be used for the DELETE request
 * @param data paremeters to be used (JSON format) as a string
 *///from   ww w .  ja  va2  s  .  co m
@SuppressWarnings("unchecked")
public void sendDelete(final String path, final String data) {
    String fullpath = path;

    if (path.startsWith("/"))
        fullpath = baseUrl + path;

    log.info("Sending DELETE request to " + fullpath);

    final DeleteMethod method = new DeleteMethod(fullpath);

    for (final Map.Entry<String, String> header : requestHeaders.entrySet())
        method.setRequestHeader(header.getKey(), header.getValue());

    if (data != null) {
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONHelper.toJSONObject(data);

            for (final Iterator<String> iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
                final String param = iterator.next();
                HttpMethodParams methodParams = new HttpMethodParams();
                methodParams.setParameter(param,
                        (jsonObject.get(param) != null) ? jsonObject.get(param).toString() : null);
                method.setParams(methodParams);

            }
        } catch (final ParseException e) {
            log.error("Sorry, parameters are not proper JSON...", e);
        }

    }
    try {
        if (nonProxyHost != null && fullpath.contains(nonProxyHost)) {
            httpClient.getHostConfiguration().setProxyHost(null);
        }
        final int statusCode = httpClient.executeMethod(method);
        response = new ResponseWrapper(method.getResponseBodyAsString(), method.getResponseHeaders(),
                statusCode);
    } catch (final IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.inbravo.scribe.rest.service.crm.ZDRESTCRMService.java

@Override
public final boolean deleteObject(final ScribeCommandObject cADCommandObject, final String idToBeDeleted)
        throws Exception {

    logger.debug("----Inside deleteObject");
    DeleteMethod deleteMethod = null;
    try {//w  w  w . java2  s . c  om
        String serviceURL = null;
        String serviceProtocol = null;
        String userId = null;
        String password = null;
        String sessionId = null;
        String crmPort = "80";

        /* Check if CrmUserId is present in request */
        if (cADCommandObject.getCrmUserId() != null) {

            /* Get agent from session manager */
            final ScribeCacheObject agent = zDCRMSessionManager
                    .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId());

            /* Get CRM information from agent */
            serviceURL = agent.getScribeMetaObject().getCrmServiceURL();
            serviceProtocol = agent.getScribeMetaObject().getCrmServiceProtocol();
            userId = agent.getScribeMetaObject().getCrmUserId();
            password = agent.getScribeMetaObject().getCrmPassword();
            sessionId = agent.getScribeMetaObject().getCrmSessionId();
            crmPort = agent.getScribeMetaObject().getCrmPort();
        }

        /* Check if id is available in request */
        if (idToBeDeleted == null) {
            /* Inform user about invalid request */
            throw new ScribeException(
                    ScribeResponseCodes._1008 + "CRM object id for deletion purpose is not present in request");
        }

        /* Create Zen desk URL */
        final String zenDeskURL = serviceProtocol + "://" + serviceURL + "/" + cADCommandObject.getObjectType()
                + "s/" + idToBeDeleted.trim() + ".xml";

        logger.debug("----Inside deleteObject zenDeskURL: " + zenDeskURL);

        /* Instantiate delete method */
        deleteMethod = new DeleteMethod(zenDeskURL);

        /* Set request content type */
        deleteMethod.addRequestHeader("Content-Type", "application/xml");
        deleteMethod.addRequestHeader("accept", "application/xml");

        /* Cookie is required to be set for session management */
        deleteMethod.addRequestHeader("Cookie", sessionId);

        final HttpClient httpclient = new HttpClient();

        /* Set credentials */
        httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)),
                new UsernamePasswordCredentials(userId, password));

        /* Execute method */
        int result = httpclient.executeMethod(deleteMethod);
        logger.debug("----Inside deleteObject response code: " + result + " & body: "
                + deleteMethod.getResponseBodyAsString());

        /* Check if object is updated */
        if (result == HttpStatus.SC_OK || result == HttpStatus.SC_CREATED) {

            /* Return the original object */
            return true;
        } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED
                || result == HttpStatus.SC_NOT_ACCEPTABLE) {
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : "
                    + ZDCRMMessageFormatUtils.getErrorFromResponse(deleteMethod.getResponseBodyAsStream()));
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM");
        } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {
            throw new ScribeException(ScribeResponseCodes._1004
                    + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct");
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final ParserConfigurationException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final SAXException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final IOException exception) {
        throw new ScribeException(
                ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                exception);
    } finally {
        /* Release connection socket */
        if (deleteMethod != null) {
            deleteMethod.releaseConnection();
        }
    }
    return false;
}