Example usage for org.apache.http.client.methods HttpDelete HttpDelete

List of usage examples for org.apache.http.client.methods HttpDelete HttpDelete

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpDelete HttpDelete.

Prototype

public HttpDelete(final String uri) 

Source Link

Usage

From source file:in.huohua.peterson.network.NetworkUtils.java

public static HttpResponse httpQuery(final HttpRequest request) throws ClientProtocolException, IOException {
    final HttpRequestBase requestBase;
    if (request.getHttpMethod().equals(HttpRequest.HTTP_METHOD_GET)) {
        final StringBuilder builder = new StringBuilder(request.getUrl());
        if (request.getParams() != null) {
            if (!request.getUrl().contains("?")) {
                builder.append("?");
            } else {
                builder.append("&");
            }//from w ww.j a v  a  2  s .  c o  m
            builder.append(request.getParamsAsString());
        }
        final HttpGet get = new HttpGet(builder.toString());
        requestBase = get;
    } else if (request.getHttpMethod().equals(HttpRequest.HTTP_METHOD_POST)) {
        final HttpPost post = new HttpPost(request.getUrl());
        if (request.getEntity() != null) {
            post.setEntity(request.getEntity());
        } else {
            post.setEntity(new UrlEncodedFormEntity(request.getParamsAsList(), "UTF-8"));
        }
        requestBase = post;
    } else if (request.getHttpMethod().equals(HttpRequest.HTTP_METHOD_PUT)) {
        final HttpPut put = new HttpPut(request.getUrl());
        if (request.getEntity() != null) {
            put.setEntity(request.getEntity());
        } else {
            put.setEntity(new UrlEncodedFormEntity(request.getParamsAsList(), "UTF-8"));
        }
        requestBase = put;
    } else if (request.getHttpMethod().equals(HttpRequest.HTTP_METHOD_DELETE)) {
        final StringBuilder builder = new StringBuilder(request.getUrl());
        if (request.getParams() != null) {
            if (!request.getUrl().contains("?")) {
                builder.append("?");
            } else {
                builder.append("&");
            }
            builder.append(request.getParamsAsString());
        }
        final HttpDelete delete = new HttpDelete(builder.toString());
        requestBase = delete;
    } else {
        return null;
    }

    if (request.getHeaders() != null) {
        final Iterator<Map.Entry<String, String>> iterator = request.getHeaders().entrySet().iterator();
        while (iterator.hasNext()) {
            final Map.Entry<String, String> kv = iterator.next();
            requestBase.setHeader(kv.getKey(), kv.getValue());
        }
    }
    return HTTP_CLIENT.execute(requestBase);
}

From source file:br.com.vpsa.oauth2android.token.BearerTokenTypeDefinition.java

@Override
public HttpDelete getAuthorizedHttpDelete(List<NameValuePair> additionalParameter, String requestUri,
        Server server, Client client, boolean useHeader) throws InvalidTokenTypeException {
    BearerToken token = castToken(client);

    HttpDelete httpDelete;//from  w ww .  j av a 2 s  .com

    String url = server.getResourceServer() + (requestUri.startsWith("/") ? requestUri : "/" + requestUri);
    if (!additionalParameter.isEmpty()) {
        if (url.contains("?")) {
            url += "&";
        } else {
            url += "?";
        }
        for (Iterator<NameValuePair> it = additionalParameter.iterator(); it.hasNext();) {
            NameValuePair nameValuePair = it.next();
            url += nameValuePair.getName() + "=" + nameValuePair.getValue();
            if (it.hasNext()) {
                url += "&";
            }
        }
    }
    if (useHeader) {
        httpDelete = new HttpDelete(url);
        httpDelete.addHeader(authorizationHeader(token));
    } else {
        if (url.contains("?")) {
            url += "&access_token=" + token.getToken();
        } else {
            url += "?access_token=" + token.getToken();
        }
        httpDelete = new HttpDelete(url);
    }
    return httpDelete;
}

From source file:com.supremainc.biostar2.sdk.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///w w  w. j  ava  2 s  . co m
@SuppressWarnings("deprecation")
/* protected */static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for
        // backwards compatibility.
        // If the request's post body is null, then the assumption is
        // that the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Method.HEAD:
        return new HttpHead(request.getUrl());
    case Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Method.TRACE:
        return new HttpTrace(request.getUrl());
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:com.sinacloud.scs.http.HttpRequestFactory.java

/**
 * Creates an HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the original request.
 *
 * @param request/*w  w w .  j  a va2 s  . c o m*/
 *            The request to convert to an HttpClient method object.
 * @param previousEntity
 *            The optional, previous HTTP entity to reuse in the new
 *            request.
 * @param context
 *            The execution context of the HTTP method to be executed
 *
 * @return The converted HttpClient method object with any parameters,
 *         headers, etc. from the original request set.
 */
HttpRequestBase createHttpRequest(Request<?> request, ClientConfiguration clientConfiguration,
        HttpEntity previousEntity, ExecutionContext context) {
    URI endpoint = request.getEndpoint();

    /*
     * HttpClient cannot handle url in pattern of "http://host//path", so we
     * have to escape the double-slash between endpoint and resource-path
     * into "/%2F"
     */
    String uri = HttpUtils.appendUri(endpoint.toString(), request.getResourcePath(), true);
    String encodedParams = HttpUtils.encodeParameters(request);

    /*
     * For all non-POST requests, and any POST requests that already have a
     * payload, we put the encoded params directly in the URI, otherwise,
     * we'll put them in the POST request's payload.
     */
    boolean requestHasNoPayload = request.getContent() != null;
    boolean requestIsPost = request.getHttpMethod() == HttpMethodName.POST;
    boolean putParamsInUri = !requestIsPost || requestHasNoPayload;
    if (encodedParams != null && putParamsInUri) {
        uri += "?" + encodedParams;
    }

    HttpRequestBase httpRequest;
    if (request.getHttpMethod() == HttpMethodName.POST) {
        HttpPost postMethod = new HttpPost(uri);

        /*
         * If there isn't any payload content to include in this request,
         * then try to include the POST parameters in the query body,
         * otherwise, just use the query string. For all AWS Query services,
         * the best behavior is putting the params in the request body for
         * POST requests, but we can't do that for S3.
         */
        if (request.getContent() == null && encodedParams != null) {
            postMethod.setEntity(newStringEntity(encodedParams));
        } else {
            postMethod.setEntity(new RepeatableInputStreamRequestEntity(request));
        }
        httpRequest = postMethod;
    } else if (request.getHttpMethod() == HttpMethodName.PUT) {
        HttpPut putMethod = new HttpPut(uri);
        httpRequest = putMethod;

        /*
         * Enable 100-continue support for PUT operations, since this is
         * where we're potentially uploading large amounts of data and want
         * to find out as early as possible if an operation will fail. We
         * don't want to do this for all operations since it will cause
         * extra latency in the network interaction.
         */
        putMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

        if (previousEntity != null) {
            putMethod.setEntity(previousEntity);
        } else if (request.getContent() != null) {
            HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
            if (request.getHeaders().get("Content-Length") == null) {
                entity = newBufferedHttpEntity(entity);
            }
            putMethod.setEntity(entity);
        }
    } else if (request.getHttpMethod() == HttpMethodName.GET) {
        httpRequest = new HttpGet(uri);
    } else if (request.getHttpMethod() == HttpMethodName.DELETE) {
        httpRequest = new HttpDelete(uri);
    } else if (request.getHttpMethod() == HttpMethodName.HEAD) {
        httpRequest = new HttpHead(uri);
    } else {
        throw new SCSClientException("Unknown HTTP method name: " + request.getHttpMethod());
    }

    configureHeaders(httpRequest, request, context, clientConfiguration);

    return httpRequest;
}

From source file:org.fcrepo.integration.api.FedoraDatastreamsIT.java

License:asdf

@Test
public void testDeleteDatastream() throws Exception {
    execute(postObjMethod("FedoraDatastreamsTest5"));

    final HttpPost method = postDSMethod("FedoraDatastreamsTest5", "ds1", "foo");
    assertEquals(201, getStatus(method));

    final HttpGet method_2 = new HttpGet(serverAddress + "objects/FedoraDatastreamsTest5/datastreams/ds1");
    assertEquals(200, getStatus(method_2));

    final HttpDelete dmethod = new HttpDelete(serverAddress + "objects/FedoraDatastreamsTest5/datastreams/ds1");
    assertEquals(204, getStatus(dmethod));

    final HttpGet method_test_get = new HttpGet(
            serverAddress + "objects/FedoraDatastreamsTest5/datastreams/ds1");
    assertEquals(404, getStatus(method_test_get));
}

From source file:org.dasein.cloud.skeleton.RESTMethod.java

public void delete(@Nonnull String resource, @Nonnull String id, @Nullable NameValuePair... parameters)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + RESTMethod.class.getName() + ".delete(" + resource + "," + id + ","
                + Arrays.toString(parameters) + ")");
    }//from ww  w  .ja v a2 s  . c  o m
    try {
        String target = getEndpoint(resource, id, parameters);

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [DELETE (" + (new Date()) + ")] -> " + target
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            URI uri;

            try {
                uri = new URI(target);
            } catch (URISyntaxException e) {
                throw new ConfigurationException(e);
            }
            HttpClient client = getClient(uri);

            try {
                ProviderContext ctx = provider.getContext();

                if (ctx == null) {
                    throw new NoContextException();
                }
                HttpDelete delete = new HttpDelete(target);

                long timestamp = System.currentTimeMillis();

                String signature = getSignature(ctx.getAccessPublic(), ctx.getAccessPrivate(), "DELETE",
                        resource, id, timestamp);

                try {
                    delete.addHeader(ACCESS_KEY_HEADER, new String(ctx.getAccessPublic(), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new InternalException(e);
                }
                delete.addHeader("Accept", "application/json");
                delete.addHeader(SIGNATURE_HEADER, signature);
                delete.addHeader(VERSION_HEADER, VERSION);

                if (wire.isDebugEnabled()) {
                    wire.debug(delete.getRequestLine().toString());
                    for (Header header : delete.getAllHeaders()) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }
                    wire.debug("");
                }
                HttpResponse response;
                StatusLine status;

                try {
                    APITrace.trace(provider, "DELETE " + resource);
                    response = client.execute(delete);
                    status = response.getStatusLine();
                } catch (IOException e) {
                    logger.error("Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("HTTP Status " + status);
                }
                Header[] headers = response.getAllHeaders();

                if (wire.isDebugEnabled()) {
                    wire.debug(status.toString());
                    for (Header h : headers) {
                        if (h.getValue() != null) {
                            wire.debug(h.getName() + ": " + h.getValue().trim());
                        } else {
                            wire.debug(h.getName() + ":");
                        }
                    }
                    wire.debug("");
                }
                if (status.getStatusCode() == NOT_FOUND) {
                    throw new CloudException("No such endpoint: " + target);
                }
                if (status.getStatusCode() != NO_CONTENT) {
                    logger.error("Expected NO CONTENT for DELETE request, got " + status.getStatusCode());
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new CloudProviderException(CloudErrorType.GENERAL, status.getStatusCode(),
                                status.getReasonPhrase(), status.getReasonPhrase());
                    }
                    String body;

                    try {
                        body = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new CloudProviderException(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(body);
                    }
                    wire.debug("");
                    throw new CloudProviderException(CloudErrorType.GENERAL, status.getStatusCode(),
                            status.getReasonPhrase(), body);
                }
            } finally {
                try {
                    client.getConnectionManager().shutdown();
                } catch (Throwable ignore) {
                }
            }
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [DELETE (" + (new Date()) + ")] -> " + target
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + RESTMethod.class.getName() + ".delete()");
        }
    }
}

From source file:com.upyun.sdk.utils.HttpClientUtils.java

private static HttpResponse delete(String url, HttpClient httpclient, Map<String, String> headers) {

    HttpResponse response = null;// ww w  .j a  v  a  2  s.  c  om

    try {
        httpclient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);// 
        httpclient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, SO_TIMEOUT); // ?

        HttpDelete httpDelete = new HttpDelete(url);

        for (String key : headers.keySet()) {
            httpDelete.addHeader(key, headers.get(key));
        }

        response = httpclient.execute(httpDelete);
    } catch (Exception e) {
        LogUtil.exception(logger, e);
    }

    return response;
}

From source file:org.fcrepo.auth.roles.basic.integration.AbstractBasicRolesIT.java

protected HttpDelete deleteObjMethod(final String param) {
    final HttpDelete delete = new HttpDelete(serverAddress + param);
    logger.debug("DELETE: {}", delete.getURI());
    return delete;
}

From source file:org.wso2.carbon.dynamic.client.web.app.registration.util.RemoteDCRClient.java

public static boolean deleteOAuthApplication(String user, String appName, String clientid, String host)
        throws DynamicClientRegistrationException {
    if (log.isDebugEnabled()) {
        log.debug("Invoking DCR service to remove OAuth application created for web app : " + appName);
    }//from w  w  w.  ja  v  a2 s  . c  o m
    DefaultHttpClient httpClient = getHTTPSClient();
    try {
        URI uri = new URIBuilder().setScheme(
                DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_PROTOCOL)
                .setHost(host)
                .setPath(
                        DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT)
                .setParameter("applicationName", appName).setParameter("userId", user)
                .setParameter("consumerKey", clientid).build();
        HttpDelete httpDelete = new HttpDelete(uri);
        HttpResponse response = httpClient.execute(httpDelete);
        int status = response.getStatusLine().getStatusCode();
        if (status == 200) {
            return true;
        }
    } catch (IOException e) {
        throw new DynamicClientRegistrationException(
                "Connection error occurred while constructing the payload for "
                        + "invoking DCR endpoint for unregistering the web-app : " + appName,
                e);
    } catch (URISyntaxException e) {
        throw new DynamicClientRegistrationException(
                "Exception occurred while constructing the URI for invoking "
                        + "DCR endpoint for unregistering the web-app : " + appName,
                e);
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
    return false;
}

From source file:RestApiHttpClient.java

/**
 * Make a REST-Api Call with given HTTP-Method, Path and Data
 * //  w w  w.j  a va 2  s .c o  m
 * @param method HTTP-Method (GET, POST, PUT and DELETE)
 * @param path String URL path with additional Parameters (articles/3)
 * @param data String POST or PUT data or null
 * @return String
 * @throws IOException in case of a problem or the connection was aborted
 */
public String call(RestApiHttpClient.HTTP_METHOD method, String path, String data) throws IOException {
    HttpRequestBase httpquery;

    switch (method) {
    case POST: {
        httpquery = new HttpPost(this.apiEndpoint + path);
        StringEntity sendData = new StringEntity(data,
                ContentType.create(ContentType.APPLICATION_JSON.getMimeType(), "UTF-8"));

        ((HttpPost) httpquery).setEntity(sendData);

        break;
    }
    case PUT: {
        httpquery = new HttpPut(this.apiEndpoint + path);
        if (data != null) {
            StringEntity sendData = new StringEntity(data,
                    ContentType.create(ContentType.APPLICATION_JSON.getMimeType(), "UTF-8"));
            ((HttpPut) httpquery).setEntity(sendData);
        }

        break;
    }
    case DELETE: {
        httpquery = new HttpDelete(this.apiEndpoint + path);
        break;
    }
    default:
        httpquery = new HttpGet(this.apiEndpoint.toString() + path);
        break;
    }

    CloseableHttpResponse response = httpclient.execute(httpquery, this.localContext);

    String result = EntityUtils.toString(response.getEntity());
    response.close();

    return result;
}