GET request with request body in OkHttp

I am trying to use OkHttp 3.6.0 with Elasticsearch and I am stuck with sending requests to the Elasticsearch Multi GET API .

A HTTP GET request with the request body is required. Unfortunately, OkHttp does not support this out of the box and throws an exception if I try to build a query 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 the request body in OkHttp?

Related issues:

+5
source share
2 answers

I found a solution to this problem after several attempts. Maybe someone will find this useful.

"Httpurl.Builder".

HttpUrl mySearchUrl = new HttpUrl.Builder()
       .scheme("https")
       .host("www.google.com")
       .addPathSegment("search")
       .addQueryParameter("q", "polar bears")
       .build();

URL :

https://www.google.com/search?q=polar%20bears

URL :

Request request = new Request.Builder()
                        .url(mySearchUrl)
                        .addHeader("Accept", "application/json")
                        .method("GET", null)
                        .build();

: https://square.imtqy.com/okhttp/3.x/okhttp/okhttp3/HttpUrl.html

+1

, , , , , .

, POST "GET" , . .

- :

Builder builder = new Request.Builder().url(mySearchUrl).method("POST", body).build();
Field field = Builder.class.getField("method");
field.setAccessible(true);
field.setValue(builder, "GET");
0

Source: https://habr.com/ru/post/1674345/


All Articles