Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GET request with request body in OkHttp

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:

  • HTTP GET with request body
  • How to make OKHTTP post request without a request body?
  • Elasticsearch GET request with request body
like image 574
joschi Avatar asked Apr 07 '17 23:04

joschi


People also ask

How do you get a response body from OkHttp?

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.

Can we send body GET request?

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.

What is the use of OkHttp in Android?

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.

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.


1 Answers

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

  1. I tried request rewriting using network interceptor

  2. 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.

like image 141
NILESH SALPE Avatar answered Sep 20 '22 13:09

NILESH SALPE