Is there any way to make a post request with OkHTTP that does not have a request body?
            Asked
            
        
        
            Active
            
        
            Viewed 3.3k times
        
    5 Answers
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
- 
                    17
- 
                    8or `RequestBody.create("", null)`, if you're using the latest version and don't like deprecation warnings. :) – JakeRobb Sep 17 '19 at 03:06
- 
                    Try `"".toRequestBody()` or `"".toRequestBody("application/json".toMediaTypeOrNull())` – Alex Nov 10 '19 at 20:45
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
- 
                    
- 
                    `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
- 
                    3This 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
 
    
    
        anubhav choudhary
        
- 31
- 2
