0

So my question is how can I create a DELETE Request to an URL in Android Studio Java. I already have an Async Task which GET json from URL. So my question now is how can I create a DELETE request

EDIT:

So right now I got this code:

   int pos = arrlist.get(info.position).getId();
                    URL_DELETE = "http://testserver/test/tesst.php?id=" + pos + "&username=" + username + "&password=" + password;
                    URL url = null;
                    try {
                        url = new URL(URL_DELETE);
                        HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
                        httpCon.setDoOutput(true);
                        httpCon.setRequestProperty(
                                "Content-Type", "application/x-www-form-urlencoded" );
                        httpCon.setRequestMethod("DELETE");

                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (ProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

To understand the content of the given URL should be deleted. But if I run the code nothing happens.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
private432
  • 19
  • 5

2 Answers2

2

You need to call connect() on the HttpURLConnection. Right now you're not actually making a connection to the server.

Based on your comments on the other answer, you're also trying to run this code on the main (UI) thread - you'll need to change your code to run on a background thread.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
1

If you're using OkHttp:

Request request = new Request.Builder().delete().url(url).build();
Response rawResponse = null;
try {
      rawResponse = new OkHttpClient().newCall(request).execute();
} catch (IOException e) {
    System.err.println(e.getMessage());
}

String responseAsString = rawResponse.body().string();
hd1
  • 33,938
  • 5
  • 80
  • 91