Sending HTTP DELETE request in Android

后端 未结 9 1604
悲哀的现实
悲哀的现实 2020-12-15 04:02

My client\'s API specifies that to remove an object, a DELETE request must be sent, containing Json header data describing the content. Effectively it\'s the same call as ad

相关标签:
9条回答
  • 2020-12-15 04:19

    Here is my Delete request method.

    Simply it is post request with extra RequestProperty

    connection.setRequestProperty("X-HTTP-Method-Override", "DELETE");
    

    Below the complete method.

        public void executeDeleteRequest(String stringUrl, JSONObject jsonObject, String reqContentType, String resContentType, int timeout) throws Exception {
        URL url = new URL(stringUrl);
        HttpURLConnection connection = null;
        String urlParameters = jsonObject.toString();
        try {
            connection = (HttpURLConnection) url.openConnection();
    
            //Setting the request properties and header
            connection.setRequestProperty("X-HTTP-Method-Override", "DELETE");
            connection.setRequestMethod("POST");
            connection.setRequestProperty("User-Agent", USER_AGENT);
            connection.setRequestProperty(CONTENT_TYPE_KEY, reqContentType);
            connection.setRequestProperty(ACCEPT_KEY, resContentType);
    
    
            connection.setReadTimeout(timeout);
            connection.setConnectTimeout(defaultTimeOut);
    
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
    
            // Send request
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();
            responseCode = connection.getResponseCode();
            // To handle web services which server responds with response code
            // only
            try {
                response = convertStreamToString(connection.getInputStream());
            } catch (Exception e) {
                Log.e(Log.TAG_REST_CLIENT, "Cannot convert the input stream to string for the url= " + stringUrl + ", Code response=" + responseCode + "for the JsonObject: " + jsonObject.toString(), context);
            }
        } catch (
                Exception e
                )
    
        {
            if (!BController.isInternetAvailable(context)) {
                IntentSender.getInstance().sendIntent(context, Constants.BC_NO_INTERNET_CONNECTION);
                Log.e(Log.TAG_REST_CLIENT, "No internet connection", context);
            }
            Log.e(Log.TAG_REST_CLIENT, "Cannot perform the POST request successfully for the following URL: " + stringUrl + ", Code response=" + responseCode + "for the JsonObject: " + jsonObject.toString(), context);
            throw e;
        } finally{
    
            if (connection != null) {
                connection.disconnect();
            }
        }
    
    }
    

    I hope it helped.

    0 讨论(0)
  • 2020-12-15 04:20

    You can't just use the addHeader() method?

    0 讨论(0)
  • 2020-12-15 04:23

    getOutputStream() only works on requests that have a body, like POST. Using it on requests that don't have a body, like DELETE, will throw a ProtocolException. Instead, you should add your headers with addHeader() instead of calling getOutputStream().

    0 讨论(0)
  • 2020-12-15 04:27

    I know is a bit late, but if anyone falls here searching on google like me I solved this way:

        conn.setRequestProperty("X-HTTP-Method-Override", "DELETE");
        conn.setRequestMethod("POST");
    
    0 讨论(0)
  • 2020-12-15 04:31

    DELETE request is an extended form of GET request, as per the android documentation you cannot write in the body of DELETE request. HttpUrlConnection will throw "unable to write protocol exception".

    If you still want to write the parameter in the body, i suggest you to use the OKHttp Library.

    OKHttp documentation

    If you are intrested to use more simpler library then you can try SimpleHttpAndroid library

    One thing to remember here is if you are not writing anything in the body then remove the line

    conn.setDoOutput(true);
    

    Thanks, Hopefully it may help.

    0 讨论(0)
  • 2020-12-15 04:31

    To add closure to this question, it transpired that there is no supported method to send an HTTP DELETE request containing header data.

    The solution was for the client to alter their API to accept a standard GET request which indicated that the action should be a delete, containing the id of the item to be deleted.

    http://clienturl.net/api/delete/id12345
    
    0 讨论(0)
提交回复
热议问题