jos*_*chi 6 java okhttp okhttp3
我正在尝试将OkHttp 3.6.0与Elasticsearch一起使用,而我却不得不向Elasticsearch Multi GET API发送请求.
它需要向请求主体发送HTTP GET请求.不幸的是,如果我自己尝试构建请求,OkHttp不支持开箱即用并抛出异常.
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();
Run Code Online (Sandbox Code Playgroud)
有没有机会在OkHttp中使用请求主体建立GET请求?
相关问题:
经过几次尝试,我找到了解决这个问题的方法。也许有人觉得它有用。
我使用了“Httpurl.Builder”。
HttpUrl mySearchUrl = new HttpUrl.Builder()
.scheme("https")
.host("www.google.com")
.addPathSegment("search")
.addQueryParameter("q", "polar bears")
.build();
Run Code Online (Sandbox Code Playgroud)
你的 get 请求 url 将会以这种方式发生:
https://www.google.com/search?q=polar%20bears
Run Code Online (Sandbox Code Playgroud)
构建您的网址后,您必须像这样构建您的请求:
Request request = new Request.Builder()
.url(mySearchUrl)
.addHeader("Accept", "application/json")
.method("GET", null)
.build();
Run Code Online (Sandbox Code Playgroud)
这是来源:https://square.github.io/okhttp/3.x/okhttp/okhttp3/HttpUrl.html
归档时间: |
|
查看次数: |
7202 次 |
最近记录: |