How to make OKHTTP post request without a request body?

26,630

Solution 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

This worked for me:

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

Solution 3

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

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

Solution 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()
Share:
26,630

Related videos on Youtube

Justcurious
Author by

Justcurious

Java Developer

Updated on March 30, 2022

Comments

  • Justcurious
    Justcurious over 2 years

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

  • Ravindra Kushwaha
    Ravindra Kushwaha over 8 years
    is it yours answer or question??
  • mr5
    mr5 about 7 years
    or RequestBody.create(null, "")
  • JakeRobb
    JakeRobb almost 5 years
    or RequestBody.create("", null), if you're using the latest version and don't like deprecation warnings. :)
  • Alex
    Alex over 4 years
    Try "".toRequestBody() or "".toRequestBody("application/json".toMediaTypeOrNull())
  • netcyrax
    netcyrax over 4 years
    This answer is for kotlin btw. If the IDE doesn't recognize this, you must import the extension function: import okhttp3.RequestBody.Companion.toRequestBody
  • David
    David almost 3 years
    Perfect! Thanks
  • Tgo1014
    Tgo1014 about 2 years
    Using this EMPTY_REQUEST caused some weird ClassNotFound exception