'How to make OKHTTP post request without a request body?

Is there any way to make a post request with OkHTTP that does not have a request body?



Solution 1:[1]

    RequestBody reqbody = RequestBody.create(null, new byte[0]);  
    Request.Builder formBody = new Request.Builder().url(url).method("POST",reqbody).header("Content-Length", "0");
    clientOk.newCall(formBody.build()).enqueue(OkHttpCallBack());

Solution 2:[2]

This worked for me:

RequestBody body = RequestBody.create(null, new byte[]{});

Solution 3:[3]

  • "".toRequestBody()
  • "".toRequestBody("application/json".toMediaTypeOrNull())

...depends on which media type your endpoint expects.

Solution 4:[4]

I'm using okhttp3.

You can also do this for an empty request body:

val empty: RequestBody = EMPTY_REQUEST

For a POST:

val request = Request.Builder().url(http).post(EMPTY_REQUEST).build()

Solution 5:[5]

The below method with the arguments arguments has been deprecated in okhhtp3.

RequestBody.create(null, new byte[0])

The below solution worked for me.

RequestBody.create("",null)) 

Request.Builder().url(errorRetryUrl).post(RequestBody.create("",null)).build()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nikola Despotoski
Solution 2 rHenderson
Solution 3 Alex
Solution 4 Mobile Ben
Solution 5 Sreeram TP