Sending HTTP DELETE request in Android

后端 未结 9 1605
悲哀的现实
悲哀的现实 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:38

    Try below method for call HttpDelete method, it works for me, hoping that work for you as well

    String callHttpDelete(String url){
    
                 try {
                        HttpParams httpParams = new BasicHttpParams();
                        HttpConnectionParams.setConnectionTimeout(httpParams, 15000);
                        HttpConnectionParams.setSoTimeout(httpParams, 15000);
    
                        //HttpClient httpClient = getNewHttpClient();
                        HttpClient httpClient = new DefaultHttpClient();// httpParams);
    
    
                        HttpResponse response = null;    
                        HttpDelete httpDelete = new HttpDelete(url);    
                        response = httpClient.execute(httpDelete); 
    
                        String sResponse;
    
                        StringBuilder s = new StringBuilder();
    
                        while ((sResponse = reader.readLine()) != null) {
                            s = s.append(sResponse);
                        }
    
                        Log.v(tag, "Yo! Response recvd ["+s.toString()+"]");
                        return s.toString();
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                  return s.toString();
            }
    
    0 讨论(0)
  • 2020-12-15 04:40

    The problematic line is con.setDoOutput(true);. Removing that will fix the error.

    You can add request headers to a DELETE, using addRequestProperty or setRequestProperty, but you cannot add a request body.

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

    This is a limitation of HttpURLConnection, on old Android versions (<=4.4).

    While you could alternatively use HttpClient, I don't recommend it as it's an old library with several issues that was removed from Android 6.

    I would recommend using a new recent library like OkHttp:

    OkHttpClient client = new OkHttpClient();
    Request.Builder builder = new Request.Builder()
        .url(getYourURL())
        .delete(RequestBody.create(
            MediaType.parse("application/json; charset=utf-8"), getYourJSONBody()));
    
    Request request = builder.build();
    
    try {
        Response response = client.newCall(request).execute();
        String string = response.body().string();
        // TODO use your response
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    0 讨论(0)
提交回复
热议问题