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() 

Source Link

Usage

From source file:com.appdynamics.demo.gasp.service.RESTIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Uri action = intent.getData();//from  w  ww .  j  av a  2 s .com
    Bundle extras = intent.getExtras();

    if (extras == null || action == null || !extras.containsKey(EXTRA_RESULT_RECEIVER)) {
        Log.e(TAG, "You did not pass extras or data with the Intent.");
        return;
    }

    int verb = extras.getInt(EXTRA_HTTP_VERB, GET);
    Bundle params = extras.getParcelable(EXTRA_PARAMS);
    Bundle headers = extras.getParcelable(EXTRA_HEADERS);
    ResultReceiver receiver = extras.getParcelable(EXTRA_RESULT_RECEIVER);

    try {
        HttpRequestBase request = null;

        // Get query params from Bundle and build URL
        switch (verb) {
        case GET: {
            request = new HttpGet();
            attachUriWithQuery(request, action, params);
        }
            break;

        case DELETE: {
            request = new HttpDelete();
            attachUriWithQuery(request, action, params);
        }
            break;

        case POST: {
            request = new HttpPost();
            request.setURI(new URI(action.toString()));

            HttpPost postRequest = (HttpPost) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                postRequest.setEntity(formEntity);
            }
        }
            break;

        case PUT: {
            request = new HttpPut();
            request.setURI(new URI(action.toString()));

            HttpPut putRequest = (HttpPut) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                putRequest.setEntity(formEntity);
            }
        }
            break;
        }

        // Get Headers from Bundle
        for (BasicNameValuePair header : paramsToList(headers)) {
            request.setHeader(header.getName(), header.getValue());
        }

        if (request != null) {
            HttpClient client = new DefaultHttpClient();

            Log.d(TAG, "Executing request: " + verbToString(verb) + ": " + action.toString());

            HttpResponse response = client.execute(request);

            HttpEntity responseEntity = response.getEntity();
            StatusLine responseStatus = response.getStatusLine();
            int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;

            if ((responseEntity != null) && (responseStatus.getStatusCode() == 200)) {
                Bundle resultData = new Bundle();
                resultData.putString(REST_RESULT, EntityUtils.toString(responseEntity));
                receiver.send(statusCode, resultData);
            } else {
                receiver.send(statusCode, null);
            }
        }
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI syntax was incorrect. " + verbToString(verb) + ": " + action.toString(), e);
        receiver.send(0, null);
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "A UrlEncodedFormEntity was created with an unsupported encoding.", e);
        receiver.send(0, null);
    } catch (ClientProtocolException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    } catch (IOException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cloudera.livy.client.http.LivyConnection.java

synchronized <V> V delete(Class<V> retType, String uri, Object... uriParams) throws Exception {
    return sendJSONRequest(new HttpDelete(), retType, uri, uriParams);
}

From source file:pt.sapo.pai.vip.VipServlet.java

@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response, () -> new HttpDelete());
}

From source file:com.cloudbees.gasp.service.RESTService.java

@Override
protected void onHandleIntent(Intent intent) {
    // When an intent is received by this Service, this method
    // is called on a new thread.

    Uri action = intent.getData();/*from  ww  w  . j  a  va2s.c o  m*/
    Bundle extras = intent.getExtras();

    if (extras == null || action == null || !extras.containsKey(EXTRA_RESULT_RECEIVER)) {
        // Extras contain our ResultReceiver and data is our REST action.  
        // So, without these components we can't do anything useful.
        Log.e(TAG, "You did not pass extras or data with the Intent.");

        return;
    }

    // We default to GET if no verb was specified.
    int verb = extras.getInt(EXTRA_HTTP_VERB, GET);
    Bundle params = extras.getParcelable(EXTRA_PARAMS);
    ResultReceiver receiver = extras.getParcelable(EXTRA_RESULT_RECEIVER);

    try {
        // Here we define our base request object which we will
        // send to our REST service via HttpClient.
        HttpRequestBase request = null;

        // Let's build our request based on the HTTP verb we were
        // given.
        switch (verb) {
        case GET: {
            request = new HttpGet();
            attachUriWithQuery(request, action, params);
        }
            break;

        case DELETE: {
            request = new HttpDelete();
            attachUriWithQuery(request, action, params);
        }
            break;

        case POST: {
            request = new HttpPost();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary. Note: some REST APIs
            // require you to POST JSON. This is easy to do, simply use
            // postRequest.setHeader('Content-Type', 'application/json')
            // and StringEntity instead. Same thing for the PUT case 
            // below.
            HttpPost postRequest = (HttpPost) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                postRequest.setEntity(formEntity);
            }
        }
            break;

        case PUT: {
            request = new HttpPut();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary.
            HttpPut putRequest = (HttpPut) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                putRequest.setEntity(formEntity);
            }
        }
            break;
        }

        if (request != null) {
            HttpClient client = new DefaultHttpClient();

            // Let's send some useful debug information so we can monitor things
            // in LogCat.
            Log.d(TAG, "Executing request: " + verbToString(verb) + ": " + action.toString());

            // Finally, we send our request using HTTP. This is the synchronous
            // long operation that we need to run on this thread.
            HttpResponse response = client.execute(request);

            HttpEntity responseEntity = response.getEntity();
            StatusLine responseStatus = response.getStatusLine();
            int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;

            // Our ResultReceiver allows us to communicate back the results to the caller. This
            // class has a method named send() that can send back a code and a Bundle
            // of data. ResultReceiver and IntentService abstract away all the IPC code
            // we would need to write to normally make this work.
            if (responseEntity != null) {
                Bundle resultData = new Bundle();
                resultData.putString(REST_RESULT, EntityUtils.toString(responseEntity));
                receiver.send(statusCode, resultData);
            } else {
                receiver.send(statusCode, null);
            }
        }
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI syntax was incorrect. " + verbToString(verb) + ": " + action.toString(), e);
        receiver.send(0, null);
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "A UrlEncodedFormEntity was created with an unsupported encoding.", e);
        receiver.send(0, null);
    } catch (ClientProtocolException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    } catch (IOException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    }
}

From source file:org.modeshape.web.jcr.rest.client.http.HttpClientConnection.java

/**
 * @param server the server with the host and port information (never <code>null</code>)
 * @param url the URL that will be used in the request (never <code>null</code>)
 * @param method the HTTP request method (never <code>null</code>)
 * @throws Exception if there is a problem establishing the connection
 *//*w  w  w  .  ja v a 2 s .  com*/
public HttpClientConnection(Server server, URL url, RequestMethod method) throws Exception {
    assert server != null;
    assert url != null;
    assert method != null;

    this.httpClient = new DefaultHttpClient();
    this.httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(server.getUser(), server.getPassword()));
    // determine the request type
    if (RequestMethod.GET == method) {
        this.request = new HttpGet();
    } else if (RequestMethod.DELETE == method) {
        this.request = new HttpDelete();
    } else if (RequestMethod.POST == method) {
        this.request = new HttpPost();
    } else if (RequestMethod.PUT == method) {
        this.request = new HttpPut();
    } else {
        throw new RuntimeException(unknownHttpRequestMethodMsg.text(method));
    }

    //set the accepts header to application/json
    this.request.setHeader("Accept", MediaType.APPLICATION_JSON);

    // set request URI
    this.request.setURI(url.toURI());
}

From source file:com.sap.core.odata.fit.ref.AbstractRefTest.java

protected HttpResponse callUri(final ODataHttpMethod httpMethod, final String uri,
        final String additionalHeader, final String additionalHeaderValue, final String requestBody,
        final String requestContentType, final HttpStatusCodes expectedStatusCode) throws Exception {

    HttpRequestBase request = httpMethod == ODataHttpMethod.GET ? new HttpGet()
            : httpMethod == ODataHttpMethod.DELETE ? new HttpDelete()
                    : httpMethod == ODataHttpMethod.POST ? new HttpPost()
                            : httpMethod == ODataHttpMethod.PUT ? new HttpPut() : new HttpPatch();
    request.setURI(URI.create(getEndpoint() + uri));
    if (additionalHeader != null) {
        request.addHeader(additionalHeader, additionalHeaderValue);
    }/*  w  w  w  .ja v  a2  s .  c o  m*/
    if (requestBody != null) {
        ((HttpEntityEnclosingRequest) request).setEntity(new StringEntity(requestBody));
        request.setHeader(HttpHeaders.CONTENT_TYPE, requestContentType);
    }

    final HttpResponse response = getHttpClient().execute(request);

    assertNotNull(response);
    assertEquals(expectedStatusCode.getStatusCode(), response.getStatusLine().getStatusCode());

    if (expectedStatusCode == HttpStatusCodes.OK) {
        assertNotNull(response.getEntity());
        assertNotNull(response.getEntity().getContent());
    } else if (expectedStatusCode == HttpStatusCodes.CREATED) {
        assertNotNull(response.getEntity());
        assertNotNull(response.getEntity().getContent());
        assertNotNull(response.getFirstHeader(HttpHeaders.LOCATION));
    } else if (expectedStatusCode == HttpStatusCodes.NO_CONTENT) {
        assertTrue(response.getEntity() == null || response.getEntity().getContent() == null);
    }

    return response;
}

From source file:com.cloudbees.gasp.loader.RESTLoader.java

@Override
public RESTResponse loadInBackground() {
    try {/* w w w.j a  v a 2 s.c  om*/
        // At the very least we always need an action.
        if (mAction == null) {
            Log.e(TAG, "You did not define an action. REST call canceled.");
            return new RESTResponse(); // We send an empty response back. The LoaderCallbacks<RESTResponse>
                                       // implementation will always need to check the RESTResponse
                                       // and handle error cases like this.
        }

        // Here we define our base request object which we will
        // send to our REST service via HttpClient.
        HttpRequestBase request = null;

        // Let's build our request based on the HTTP verb we were
        // given.
        switch (mVerb) {
        case GET: {
            request = new HttpGet();
            attachUriWithQuery(request, mAction, mParams);
        }
            break;

        case DELETE: {
            request = new HttpDelete();
            attachUriWithQuery(request, mAction, mParams);
        }
            break;

        case POST: {
            request = new HttpPost();
            request.setURI(new URI(mAction.toString()));

            // Attach form entity if necessary. Note: some REST APIs
            // require you to POST JSON. This is easy to do, simply use
            // postRequest.setHeader('Content-Type', 'application/json')
            // and StringEntity instead. Same thing for the PUT case 
            // below.
            HttpPost postRequest = (HttpPost) request;

            if (mParams != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(mParams));
                postRequest.setEntity(formEntity);
            }
        }
            break;

        case PUT: {
            request = new HttpPut();
            request.setURI(new URI(mAction.toString()));

            // Attach form entity if necessary.
            HttpPut putRequest = (HttpPut) request;

            if (mParams != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(mParams));
                putRequest.setEntity(formEntity);
            }
        }
            break;
        }

        if (request != null) {
            HttpClient client = new DefaultHttpClient();

            // Let's send some useful debug information so we can monitor things
            // in LogCat.
            Log.d(TAG, "Executing request: " + verbToString(mVerb) + ": " + mAction.toString());

            // Finally, we send our request using HTTP. This is the synchronous
            // long operation that we need to run on this Loader's thread.
            HttpResponse response = client.execute(request);

            HttpEntity responseEntity = response.getEntity();
            StatusLine responseStatus = response.getStatusLine();
            int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;

            // Here we create our response and send it back to the LoaderCallbacks<RESTResponse> implementation.
            RESTResponse restResponse = new RESTResponse(
                    responseEntity != null ? EntityUtils.toString(responseEntity) : null, statusCode);
            return restResponse;
        }

        // Request was null if we get here, so let's just send our empty RESTResponse like usual.
        return new RESTResponse();
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI syntax was incorrect. " + verbToString(mVerb) + ": " + mAction.toString(), e);
        return new RESTResponse();
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "A UrlEncodedFormEntity was created with an unsupported encoding.", e);
        return new RESTResponse();
    } catch (ClientProtocolException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        return new RESTResponse();
    } catch (IOException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        return new RESTResponse();
    }
}

From source file:com.xively.client.http.DefaultRequestHandler.java

private <T extends DomainObject> HttpRequestBase buildRequest(HttpMethod requestMethod, String appPath,
        Map<String, Object> params, T... bodyObjects) {
    AcceptedMediaType mediaType = AppConfig.getInstance().getResponseMediaType();

    HttpRequestBase request = null;//from   w w  w  .  ja  v  a  2s  .  c o m
    switch (requestMethod) {
    case DELETE:
        request = new HttpDelete();
        break;

    case GET:
        request = new HttpGet();
        break;

    case POST:
        request = new HttpPost();
        StringEntity postEntity = getEntity(false, bodyObjects);
        ((HttpPost) request).setEntity(postEntity);
        break;

    case PUT:
        request = new HttpPut();
        StringEntity putEntity = getEntity(true, bodyObjects);
        ((HttpPut) request).setEntity(putEntity);
        break;

    default:
        return null;
    }

    URIBuilder uriBuilder = buildUri(requestMethod, appPath, params, mediaType);
    try {
        request.setURI(uriBuilder.build());
    } catch (URISyntaxException e) {
        throw new RequestInvalidException("Invalid URI requested.", e);
    }

    request.addHeader("accept", mediaType.getMediaType());
    request.addHeader(HEADER_KEY_API, AppConfig.getInstance().getApiKey());
    request.addHeader(HEADER_USER_AGENT, XIVELY_USER_AGENT);

    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder();
        for (Header header : request.getAllHeaders()) {
            sb.append(header.getName()).append(",").append(header.getValue()).append(";");
        }
        log.debug(String.format("Constructed request with uri [%s], header [%s]", uriBuilder.toString(),
                sb.toString()));
    }

    return request;
}

From source file:com.andrestrequest.http.DefaultRequestHandler.java

private HttpRequestBase buildRequest(HttpMethod method, String path, Map<String, String> headers, Object body,
        Map<String, Object> params) throws UnsupportedEncodingException {
    AcceptedMediaType mediaType = AndRestConfig.getResponseMediaType();

    HttpRequestBase request = null;//from   ww w .  j a  v a 2  s.  c o m
    StringEntity entity = getEntity(body);
    switch (method) {
    case DELETE:
        request = new HttpDelete();
        break;
    case GET:
        request = new HttpGet();
        break;
    case POST:
        request = new HttpPost();
        if (entity != null) {
            ((HttpPost) request).setEntity(entity);
        }
        break;
    case PUT:
        request = new HttpPut();
        if (entity != null) {
            ((HttpPut) request).setEntity(entity);
        }
        break;
    default:
        return null;
    }

    try {
        if (!path.toLowerCase(Locale.ENGLISH).startsWith("http")) {
            URIBuilder builder = buildUri(method, path, params, mediaType);
            request.setURI(builder.build());
        } else {
            request.setURI(new URI(path));
        }
    } catch (URISyntaxException e) {
        throw new RequestInvalidException("Invalid URI requested.", e);
    }
    //      request.addHeader("accept", mediaType.getMediaType());
    //      request.addHeader(HEADER_KEY_API, AppConfig.getInstance().getApiKey());
    //      request.addHeader(HEADER_USER_AGENT, XIVELY_USER_AGENT);
    /**
     *  Header
     */
    if (headers != null && !headers.isEmpty()) {
        int index = 0;
        Header[] header = new Header[headers.size()];
        for (Entry<String, String> element : headers.entrySet()) {
            header[index++] = new BasicHeader(element.getKey(), element.getValue());
        }
        request.setHeaders(header);
    }
    //      if (params != null && !params.isEmpty()) {
    //         HttpParams hparams = new SyncBasicHttpParams();
    //         for (Entry<String, Object> param : params.entrySet()) {
    //            hparams.setParameter(param.getKey(), param.getValue());
    //         }
    //         request.setParams(hparams);
    //      }
    return request;
}

From source file:com.antew.redditinpictures.library.service.RESTService.java

@Override
protected void onHandleIntent(Intent intent) {
    Uri action = intent.getData();/*from   w  w w.  j a  v  a  2  s.c  om*/
    Bundle extras = intent.getExtras();

    if (extras == null || action == null) {
        Ln.e("You did not pass extras or data with the Intent.");
        return;
    }

    // We default to GET if no verb was specified.
    int verb = extras.getInt(EXTRA_HTTP_VERB, GET);
    RequestCode requestCode = (RequestCode) extras.getSerializable(EXTRA_REQUEST_CODE);
    Bundle params = extras.getParcelable(EXTRA_PARAMS);
    String cookie = extras.getString(EXTRA_COOKIE);
    String userAgent = extras.getString(EXTRA_USER_AGENT);

    // Items in this bundle are simply passed on in onRequestComplete
    Bundle passThrough = extras.getBundle(EXTRA_PASS_THROUGH);

    HttpEntity responseEntity = null;
    Intent result = new Intent(Constants.Broadcast.BROADCAST_HTTP_FINISHED);
    result.putExtra(EXTRA_PASS_THROUGH, passThrough);
    Bundle resultData = new Bundle();

    try {
        // Here we define our base request object which we will
        // send to our REST service via HttpClient.
        HttpRequestBase request = null;

        // Let's build our request based on the HTTP verb we were
        // given.
        switch (verb) {
        case GET: {
            request = new HttpGet();
            attachUriWithQuery(request, action, params);
        }
            break;

        case DELETE: {
            request = new HttpDelete();
            attachUriWithQuery(request, action, params);
        }
            break;

        case POST: {
            request = new HttpPost();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary. Note: some REST APIs
            // require you to POST JSON. This is easy to do, simply use
            // postRequest.setHeader('Content-Type', 'application/json')
            // and StringEntity instead. Same thing for the PUT case
            // below.
            HttpPost postRequest = (HttpPost) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                postRequest.setEntity(formEntity);
            }
        }
            break;

        case PUT: {
            request = new HttpPut();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary.
            HttpPut putRequest = (HttpPut) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                putRequest.setEntity(formEntity);
            }
        }
            break;
        }

        if (request != null) {
            DefaultHttpClient client = new DefaultHttpClient();

            // GZip requests
            // antew on 3/12/2014 - Disabling GZIP for now, need to figure this CloseGuard error:
            // 03-12 21:02:09.248    9674-9683/com.antew.redditinpictures.pro E/StrictMode A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
            //         java.lang.Throwable: Explicit termination method 'end' not called
            // at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            // at java.util.zip.Inflater.<init>(Inflater.java:82)
            // at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:96)
            // at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:81)
            // at com.antew.redditinpictures.library.service.RESTService$GzipDecompressingEntity.getContent(RESTService.java:346)
            client.addRequestInterceptor(getGzipRequestInterceptor());
            client.addResponseInterceptor(getGzipResponseInterceptor());

            if (cookie != null) {
                request.addHeader("Cookie", cookie);
            }

            if (userAgent != null) {
                request.addHeader("User-Agent", Constants.Reddit.USER_AGENT);
            }

            // Let's send some useful debug information so we can monitor things
            // in LogCat.
            Ln.d("Executing request: %s %s ", verbToString(verb), action.toString());

            // Finally, we send our request using HTTP. This is the synchronous
            // long operation that we need to run on this thread.
            HttpResponse response = client.execute(request);

            responseEntity = response.getEntity();
            StatusLine responseStatus = response.getStatusLine();
            int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;

            if (responseEntity != null) {
                resultData.putString(REST_RESULT, EntityUtils.toString(responseEntity));
                resultData.putSerializable(EXTRA_REQUEST_CODE, requestCode);
                resultData.putInt(EXTRA_STATUS_CODE, statusCode);
                result.putExtra(EXTRA_BUNDLE, resultData);

                onRequestComplete(result);
            } else {
                onRequestFailed(result, statusCode);
            }
        }
    } catch (URISyntaxException e) {
        Ln.e(e, "URI syntax was incorrect. %s %s ", verbToString(verb), action.toString());
        onRequestFailed(result, 0);
    } catch (UnsupportedEncodingException e) {
        Ln.e(e, "A UrlEncodedFormEntity was created with an unsupported encoding.");
        onRequestFailed(result, 0);
    } catch (ClientProtocolException e) {
        Ln.e(e, "There was a problem when sending the request.");
        onRequestFailed(result, 0);
    } catch (IOException e) {
        Ln.e(e, "There was a problem when sending the request.");
        onRequestFailed(result, 0);
    } finally {
        if (responseEntity != null) {
            try {
                responseEntity.consumeContent();
            } catch (IOException ignored) {
            }
        }
    }
}