GET request with request body in OkHttp

Deadly 提交于 2019-11-30 05:11:43

问题


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

回答1:


I found a solution for this problem after a few attempts. Maybe someone finds it useful.

I made use of "Httpurl.Builder."

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

Your get request url will happen exactly this way:

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

And after building your url you have to build your request like this:

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

Here is the source: https://square.github.io/okhttp/3.x/okhttp/okhttp3/HttpUrl.html




回答2:


I tried to achieve the same, but unfortunately, it cannot be done without dirty tricks I personally admire as an exercise but don't want to see in my production code.

Basically, you can create POST method with a builder and set its method field to "GET" later using the reflection. This will do the trick.

Something like this:

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


来源:https://stackoverflow.com/questions/43288236/get-request-with-request-body-in-okhttp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!