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:com.kubeiwu.commontool.khttp.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*from   ww  w. j a v a  2  s  .co  m*/
/* 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.getBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
            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;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:it.polimi.tower4clouds.rules.actions.RestCall.java

@Override
public void execute(String resourceId, String value, String timestamp) {
    getLogger().info("Action requested. Input data: {}, {}, {}", resourceId, value, timestamp);
    try {// ww w  .  j  a  v  a  2 s  .  com
        CloseableHttpClient client = HttpClients.createDefault();
        HttpUriRequest request;
        String url = getParameters().get(URL);
        String method = getParameters().get(METHOD).toUpperCase();
        switch (method) {
        case POST:
            request = new HttpPost(url);
            break;
        case PUT:
            request = new HttpPut(url);
            break;
        case DELETE:
            request = new HttpDelete(url);
            break;
        case GET:
            request = new HttpGet(url);
            break;

        default:
            getLogger().error("Unknown method {}", method);
            return;
        }
        request.setHeader("Cache-Control", "no-cache");
        CloseableHttpResponse response = client.execute(request);
        getLogger().info("Rest call executed");
        response.close();
    } catch (Exception e) {
        getLogger().error("Error executing rest call", e);
    }

}

From source file:org.sonatype.nexus.test.utils.hc4client.Hc4MethodCall.java

/**
 * Constructor./*from w ww .jav  a 2 s  . c om*/
 *
 * @param helper     The parent HTTP client helper.
 * @param method     The method name.
 * @param requestUri The request URI.
 * @param hasEntity  Indicates if the call will have an entity to send to the server.
 */
public Hc4MethodCall(Hc4ClientHelper helper, final String method, String requestUri, boolean hasEntity)
        throws IOException {
    super(helper, method, requestUri);
    this.clientHelper = helper;

    if (requestUri.startsWith("http")) {
        if (method.equalsIgnoreCase(Method.GET.getName())) {
            this.httpMethod = new HttpGet(requestUri);
        } else if (method.equalsIgnoreCase(Method.POST.getName())) {
            this.httpMethod = new HttpPost(requestUri);
        } else if (method.equalsIgnoreCase(Method.PUT.getName())) {
            this.httpMethod = new HttpPut(requestUri);
        } else if (method.equalsIgnoreCase(Method.HEAD.getName())) {
            this.httpMethod = new HttpHead(requestUri);
        } else if (method.equalsIgnoreCase(Method.DELETE.getName())) {
            this.httpMethod = new HttpDelete(requestUri);
        } else if (method.equalsIgnoreCase(Method.CONNECT.getName())) {
            // CONNECT unsupported (and is unused by legacy ITs)
            throw new UnsupportedOperationException("Not implemented");
        } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) {
            this.httpMethod = new HttpOptions(requestUri);
        } else if (method.equalsIgnoreCase(Method.TRACE.getName())) {
            this.httpMethod = new HttpTrace(requestUri);
        } else {
            // custom HTTP verbs unsupported (and is unused by legacy ITs)
            throw new UnsupportedOperationException("Not implemented");
        }

        this.httpMethod.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS,
                this.clientHelper.isFollowRedirects());
        // retry handler setting unsupported (legaacy ITs use default HC4 retry handler)
        this.responseHeadersAdded = false;
        setConfidential(this.httpMethod.getURI().getScheme().equalsIgnoreCase(Protocol.HTTPS.getSchemeName()));
    } else {
        throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here");
    }
}

From source file:org.sourcepit.docker.watcher.ConsulForwarder.java

private void deregister(ConsulService service) {
    final HttpDelete delete = new HttpDelete(uri + "/v1/agent/service/deregister/" + id(service));
    try {/*  w  ww  .  ja  v  a  2s .co  m*/
        closeQuietly(client.execute(delete));
    } catch (IOException e) {
        e.printStackTrace();
    }

    final HttpDelete delete2 = new HttpDelete(uri + "/v1/agent/service/deregister/" + getTtlCheckName(service));
    try {
        closeQuietly(client.execute(delete2));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.harlap.test.http.MockHttpServerBehaviour.java

@Test
public void testShouldHandleDeleteRequests() throws ClientProtocolException, IOException {
    // Given a mock server configured to respond to a DELETE /test
    server.expect(MockHttpServer.Method.DELETE, "/test").respondWith(204, "text/plain", "");

    // When a request for DELETE /test arrives
    HttpDelete req = new HttpDelete(baseUrl + "/test");
    HttpResponse response = client.execute(req);

    // Then the response status is 204
    assertEquals(204, response.getStatusLine().getStatusCode());
}

From source file:cn.bidaround.ytcore.util.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from  w  w  w  . j av  a 2  s .  c o  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:javaSeed.utils.jiraConnection.Cycle.java

public static Long deleteCycle(ZephyrConfigModel zephyrData) {

    Long cycleId = 0L;//  w w w .  j  a v  a2  s. c o  m

    HttpResponse response = null;
    try {
        String deleteCycleURL = URL_DELETE_CYCLE.replace("{SERVER}", zephyrData.getRestClient().getUrl())
                .replace("{id}", zephyrData.getCycleId() + "");

        HttpDelete createCycleRequest = new HttpDelete(deleteCycleURL);

        response = zephyrData.getRestClient().getHttpclient().execute(createCycleRequest,
                zephyrData.getRestClient().getContext());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode >= 200 && statusCode < 300) {
        HttpEntity entity = response.getEntity();
        @SuppressWarnings("unused")
        String string = null;
        try {
            string = EntityUtils.toString(entity);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else {
        try {
            throw new ClientProtocolException("Unexpected response status: " + statusCode);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }
    }

    return cycleId;
}

From source file:dk.i2m.drupal.resource.FileResource.java

public boolean delete(Long id) throws HttpResponseException, IOException {
    URLBuilder builder = new URLBuilder(getDc().getHostname());
    builder.add(getDc().getEndpoint());//from w  w w.ja  v  a  2 s. co m
    builder.add(getAlias());
    builder.add(id);

    HttpDelete method = new HttpDelete(builder.toURI());

    ResponseHandler<String> handler = new BasicResponseHandler();
    String response = getDc().getHttpClient().execute(method, handler);

    return Boolean.valueOf(response);
}

From source file:com.siahmsoft.soundroid.sdk7.services.UploadService.java

public void deleteTrack(Uri uri) {

    Track track = TracksManager.findTrack(getContentResolver(), uri);

    if (track != null) {
        String id = uri.getLastPathSegment();
        int rowsDeleted = getContentResolver().delete(uri, null, null);

        if (rowsDeleted > 0) {

            try {
                final HttpDelete delete = new HttpDelete(
                        "http://api.soundcloud.com/me/tracks/" + track.getmIdTrack());
                Soundroid.getSc().signRequest(delete);
                HttpResponse response = HttpManager.newInstance().execute(delete);

                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    showNotification("Track " + track.getmTitle() + " deleted");
                    Log.i(TAG, "Deleted " + rowsDeleted + " track with local id " + id + " and remote id "
                            + track.getmIdTrack());

                } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                    showNotification("Track " + track.getmTitle() + " not found");
                }/*w  w  w.  ja v a 2  s  .c o m*/

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            showNotification("Track " + uri + " not found");
        }
    }
}

From source file:com.srotya.tau.ui.rules.TemplateManager.java

public AlertTemplate deleteTemplate(UserBean ub, String tenantId, short templateId) throws Exception {
    AlertTemplate template = getTemplate(ub, tenantId, templateId);
    if (template != null) {
        try {// www. j  a  v  a 2  s .co m
            CloseableHttpClient client = Utils.buildClient(am.getBaseUrl(), am.getConnectTimeout(),
                    am.getRequestTimeout());
            HttpDelete delete = new HttpDelete(
                    am.getBaseUrl() + TEMPLATE_URL + "/" + tenantId + "/" + templateId);
            if (am.isEnableAuth()) {
                delete.addHeader(BapiLoginDAO.X_SUBJECT_TOKEN, ub.getToken());
                delete.addHeader(BapiLoginDAO.HMAC, ub.getHmac());
            }
            CloseableHttpResponse resp = client.execute(delete);
            if (!Utils.validateStatus(resp)) {
                throw new Exception("status code:" + resp.getStatusLine().getStatusCode());
            }
            return template;
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Failed to delete tenant:" + template, e);
            throw e;
        }
    } else {
        throw new NotFoundException("Tenant not found");
    }
}