Java HTTP DELETE with Request Body

前端 未结 4 1826
难免孤独
难免孤独 2021-01-20 00:44

I have an external API which uses DELETE with the body(JSON). I make use of Postman REST Client and get the delete done with request body and it works fine. I am trying to a

4条回答
  •  感动是毒
    2021-01-20 01:11

    This code worked for me:-

    • You set content type by httpCon.setRequestProperty
    • You set the request Method by httpCon.setRequestMethod
    • Write the json body into OutputStreamWriter, in my sample, i converted Java object to json using Jackson ObjectMapper

      URL url = new URL("http://localhost:8080/greeting");
      HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
      httpCon.setDoOutput(true);
      httpCon.setRequestProperty(
                      "Content-Type", "application/json");
      httpCon.setRequestMethod("DELETE");
      OutputStreamWriter out = new OutputStreamWriter(
                      httpCon.getOutputStream());
      ObjectMapper objectMapper = new ObjectMapper();
      out.write(objectMapper.writeValueAsString(new Greeting("foo")));
      out.close();
      httpCon.connect();
      

提交回复
热议问题