带有OkHttp中的请求主体的GET请求 [英] GET request with request body in OkHttp
问题描述
我正在尝试将OkHttp 3.6.0与Elasticsearch一起使用,并且无法发送请求到
I'm trying to use OkHttp 3.6.0 with Elasticsearch and I'm stuck with sending requests to the Elasticsearch Multi GET API.
它需要发送带有请求正文的HTTP GET请求.不幸的是,OkHttp不支持此功能,如果我尝试自己构建请求,则会抛出异常.
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();
是否有机会在OkHttp中使用请求主体构建GET请求?
Is there any chance to build a GET request with request body in OkHttp?
相关问题:
- HTTP GET with request body
- How to make OKHTTP post request without a request body?
- Elasticsearch GET request with request body
推荐答案
几次尝试后,我找到了解决此问题的方法.也许有人觉得它有用.
I found a solution for this problem after a few attempts. Maybe someone finds it useful.
我使用了"Httpurl.Builder".
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();
以下是来源: https://square. github.io/okhttp/3.x/okhttp/okhttp3/HttpUrl.html
这篇关于带有OkHttp中的请求主体的GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!