简体   繁体   中英

Google Http delete with body (Json)

I would like to send this JSON message below, with the HTTP DELETE method. For this project is necessary to use OAuth2. So I use the dependency google-oauth. Foreach HTTP request I use the dependency google client.

{
   "propertie" : true/false,
   "members" : [
      "String value is shown here"
   ]
}

In my project I used this code below, but I cannot send the JSON message with the HTTP DELETE method.

Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
JsonArray members = new JsonArray();
JsonPrimitive element = new JsonPrimitive("String value is shown here");
members.add(element);

JsonObject closeGroupchat = new JsonObject();
closeGroupchat.addProperty("propertie", false);
closeGroupchat.add("members", members);
Gson gson = new Gson();
HttpContent hc = new ByteArrayContent("application/json", gson.toJson(closeGroupchat).getBytes());

HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
HttpRequest httpreq = requestFactory.buildRequest(HttpMethods.DELETE, genericUrl, hc);
return httpreq.execute();

Next error occurs:

java.lang.IllegalArgumentException: DELETE with non-zero content length is not supported

Can someone help me with this problem?

Your problem is that your HTTP DELETE request contains a body, which it shouldn't. When you delete a resource, you need to supply the URL to delete. Any body in the HTTP request would be meaningless, because the intention is to instruct the server to delete a resource at a particular URL. The same thing can often happen for GET requests - a body is meaningless because you're trying to retrieve a body.

For details on HTTP DELETE request bodies, see this SO question on the subject . Note that while request bodies may technically be permitted by the HTTP spec, based on your error message, your client library doesn't allow it.

To fix the problem, try passing a null value for hc , or a value that just wraps an empty JSON string (by which I mean using "" , not "{}" ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM