I'm trying to use OkHttp 3.6.0 with Elasticsearch and I'm stuck with sending requests to the Elasticsearch Multi GET API.
It requires sending an HTTP GET request with a request body. Unfortunately OkHttp doesn't support this out of the box and throws an exception if I try to build the request myself.
RequestBody body = RequestBody.create("text/plain", "test");
// No RequestBody supported
Request request = new Request.Builder()
.url("http://example.com")
.get()
.build();
// Throws: java.lang.IllegalArgumentException: method GET must not have a request body.
Request request = new Request.Builder()
.url("http://example.com")
.method("GET", requestBody)
.build();
Is there any chance to build a GET request with request body in OkHttp?
Related questions:
OkHttp Response To implement our JSON decoder, we need to extract the JSON from the result of the service call. For this, we can access the body via the body() method of the Response object.
So, yes, you can send a body with GET, and no, it is never useful to do so. This is part of the layered design of HTTP/1.1 that will become clear again once the spec is partitioned (work in progress). Yes, you can send a request body with GET but it should not have any meaning.
OkHttp android provides an implementation of HttpURLConnection and Apache Client interfaces by working directly on a top of java Socket without using any extra dependencies.
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.
Technically RFC https://www.rfc-editor.org/rfc/rfc2616#section-9.3 says you can use the body in the get request.
What I tried before switching to another client library
I tried request rewriting using network interceptor
I tried reflection to change the method
Field field = originalRequest.getClass().getDeclaredField("method");
field.setAccessible(true);
field.set(originalRequest, "GET");
Conclusion: You will need to change the library, OKHttp doesn't have support for GET request with requests body, need to use apache client or any other client which supports this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With