Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OPTIONS/HEAD REST API request with Okhttp3

I`m writing some Rest client on Android and I met a problem - I have no idea how to make HEAD and OPTIONS requests.

There are no problems with GET/POST/PUT/DELETE/PATCH requests in OkHttp3, basically they looks like:

        request = new Request.Builder()
                .url(url)
                .headers(headerBuilder.build())
                .post(bodyBuilder.build())
                .build();

And OkHttp3 doesnt provide additional methods like head() or option().

So how can I make HEAD and OPTIONS requests using OkHttp3?

like image 772
Andrey Danilov Avatar asked Mar 14 '17 14:03

Andrey Danilov


People also ask

What is okhttp3 call?

[common]\ expect interface Call. A call is a request that has been prepared for execution. A call can be canceled. As this object represents a single request/response pair (stream), it cannot be executed twice.

What is the use of okhttp3?

OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. It comes with advanced features, such as connection pooling (if HTTP/2 isn't available), transparent GZIP compression, and response caching, to avoid the network completely for repeated requests.

What is the difference between retrofit and OkHttp?

OkHttp is a pure HTTP/SPDY client responsible for any low-level network operations, caching, requests and responses manipulation. In contrast, Retrofit is a high-level REST abstraction build on top of OkHttp. Retrofit is strongly coupled with OkHttp and makes intensive use of it.

How do I use OkHttp on Android?

First, we create the OkHttpClient instance. Then, we need to create the request via the Request object and its Builder class. Next step is to pass the request in parameter of the newcall method of the OkHttpClient instance created. OkHttp supports asynchronous and synchronous calls.


1 Answers

Found answer, may be it will be useful for someone else

OkHttp3 still has method

Builder method(String method, RequestBody body)

So OPTIONS requests looks like

        Request request = new Request.Builder()
                .url(url)
                .headers(headerBuilder.build())
                .method("OPTIONS",requestBody)
                .build();

same for HEAD

like image 94
Andrey Danilov Avatar answered Oct 13 '22 19:10

Andrey Danilov