48

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

james.garriss
  • 12,959
  • 7
  • 83
  • 96
Justcurious
  • 2,201
  • 1
  • 21
  • 36

5 Answers5

76
    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());
Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148
Justcurious
  • 2,201
  • 1
  • 21
  • 36
  • The library should offer this through an easy interface, that's crappy interface design for a popular library and common use case. But thanks for your answer. – html_programmer Oct 26 '22 at 13:09
35

This worked for me:

RequestBody body = RequestBody.create(null, new byte[]{});
rHenderson
  • 608
  • 6
  • 13
11

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()
Mobile Ben
  • 7,121
  • 1
  • 27
  • 43
  • 1
    Perfect! Thanks – David Jul 01 '21 at 18:49
  • Using this EMPTY_REQUEST caused some weird ClassNotFound exception – Tgo1014 May 12 '22 at 18:36
  • `EMPTY_REQUEST` is in the internal package (`okhttp3.internal`), so it isn't intended to be used by library users. But you can simply declare the constant in your own code like this: `val EMPTY_REQUEST = ByteArray(0).toRequestBody()`. – bcody Oct 04 '22 at 14:54
6
  • "".toRequestBody()
  • "".toRequestBody("application/json".toMediaTypeOrNull())

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

Alex
  • 8,245
  • 8
  • 46
  • 55
  • 3
    This answer is for kotlin btw. If the IDE doesn't recognize this, you must import the extension function: `import okhttp3.RequestBody.Companion.toRequestBody` – netcyrax Jan 31 '20 at 22:20
3

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()

Sreeram TP
  • 11,346
  • 7
  • 54
  • 108