43

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

james.garriss
  • 12,255
  • 6
  • 78
  • 95
Justcurious
  • 2,111
  • 1
  • 19
  • 36

5 Answers5

73
    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
  • 48,622
  • 14
  • 118
  • 147
Justcurious
  • 2,111
  • 1
  • 19
  • 36
31

This worked for me:

RequestBody body = RequestBody.create(null, new byte[]{});
rHenderson
  • 558
  • 5
  • 12
6
  • "".toRequestBody()
  • "".toRequestBody("application/json".toMediaTypeOrNull())

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

Alex
  • 7,921
  • 8
  • 41
  • 54
  • 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
6

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
  • 6,951
  • 1
  • 21
  • 38
0

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
  • 10,221
  • 6
  • 43
  • 92