How to perform a HTTP delete? All I am given is the URL

15,129

Solution 1

DELETE, PUT, OPTIONS methods are restricted by most of the servers. Here is good discussion about this topic in SO. Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

Solution 2

Actually sending HttpDelete is similar to HttpGet, first you will build the url with all parameters and then just execute the request, the following code is tested.

    StringBuilder urlBuilder = new StringBuilder(Config.SERVER)
            .append("/api/deleteInfo?").append("id=")
            .append(id);
    urlBuilder.append("&people=").append(people).toString();

    try {

        HttpClient httpClient = new DefaultHttpClient();
        HttpDelete httpDelete = new HttpDelete(urlBuilder.toString());
        HttpResponse httpResponse = httpClient.execute(httpDelete);
        HttpEntity entity = httpResponse.getEntity();
        final String response = EntityUtils.toString(entity);
        Log.d(TAG, "content = " + response);
    } catch (final Exception e) {
        e.printStackTrace();
        Log.d(TAG, "content = " + e.getMessage());
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        System.gc();
    }
Share:
15,129
Winz
Author by

Winz

Updated on June 11, 2022

Comments

  • Winz
    Winz almost 2 years

    I'm just a starter in java and would like to know how to make a HTTP Delete call to a URL. Any small piece of code or reference material would be very helpful.

    I know that the question would sound very simply, but I am in urgent of this information.

  • Winz
    Winz over 12 years
    Hi, the above method doesn't work it returns 'Bad Request'. I have tried even the DeleteMethod delete = new DeleteMethod('example.com/resource'); it doesn't for this too.
  • Winz
    Winz over 12 years
    Could you please let me know how to execute the DeleteMethod delete = new DeleteMethod('example.com/resource');
  • Winz
    Winz over 12 years
    HttpClient client = new HttpClient(); DeleteMethod del = new DeleteMethod(url); client.setConnectionTimeout(8000); client.executeMethod(del); del.setRequestHeader("Content-Type", "text/xml" );
  • Winz
    Winz over 12 years
    I had tried the above method, I know how to use the Get method and that works fine without any issues.
  • jamesmortensen
    jamesmortensen over 12 years
    Additionally, some servers don't accept DELETE requests with a request-body. So it's not just browsers we need to be weary of. +1
  • 5er
    5er about 10 years
    can you tell me where to put headres? like BasicHeader(HTTP.CONTENT_TYPE, "application/json")