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()
Related videos on Youtube
Comments
-
Justcurious over 2 years
Is there any way to make a post request with OkHTTP that does not have a request body?
-
Ravindra Kushwaha over 8 yearsis it yours answer or question??
-
mr5 about 7 yearsor
RequestBody.create(null, "")
-
JakeRobb almost 5 yearsor
RequestBody.create("", null)
, if you're using the latest version and don't like deprecation warnings. :) -
Alex over 4 yearsTry
"".toRequestBody()
or"".toRequestBody("application/json".toMediaTypeOrNull())
-
netcyrax over 4 yearsThis answer is for kotlin btw. If the IDE doesn't recognize this, you must import the extension function:
import okhttp3.RequestBody.Companion.toRequestBody
-
David almost 3 yearsPerfect! Thanks
-
Tgo1014 about 2 yearsUsing this EMPTY_REQUEST caused some weird ClassNotFound exception