Java 如何通过 OkHttp 向 HTTP GET 请求添加查询参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30142626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add query parameters to a HTTP GET request by OkHttp?
提问by Jerikc XIONG
I am using the latest okhttp version: okhttp-2.3.0.jar
我使用的是最新的 okhttp 版本:okhttp-2.3.0.jar
How to add query parameters to GET request in okhttp in java ?
如何在java中的okhttp中向GET请求添加查询参数?
I found a related questionabout android, but no answer here!
我发现了一个关于 android的相关问题,但这里没有答案!
采纳答案by Tim
As mentioned in the other answer, okhttp v2.4 offers new functionality that does make this possible.
正如另一个答案中提到的,okhttp v2.4 提供了新的功能,使这成为可能。
This is not possible with the current version of okhttp, there is no method provided that will handle this for you.
当前版本的 okhttp 无法做到这一点,没有提供任何方法可以为您处理此问题。
The next best thing is building an url string or an URL
object (found in java.net.URL
) with the query included yourself, and pass that to the request builder of okhttp.
下一个最好的事情是构建一个 url 字符串或一个URL
对象(在 中找到java.net.URL
),其中包含您自己的查询,并将其传递给 okhttp 的请求构建器。
As you can see, the Request.Builder can take either a String or an URL.
如您所见,Request.Builder 可以采用字符串或 URL。
Examples on how to build an url can be found at What is the idiomatic way to compose a URL or URI in Java?
可以在什么是在 Java 中编写 URL 或 URI 的惯用方法中找到有关如何构建 url 的示例?
回答by Sofi Software LLC
As of right now (okhttp 2.4), HttpUrl.Builder now has methods addQueryParameter and addEncodedQueryParameter.
截至目前(okhttp 2.4),HttpUrl.Builder 现在具有 addQueryParameter 和 addEncodedQueryParameter 方法。
回答by Vitaly Zinchenko
Use HttpUrl class's functions:
使用 HttpUrl 类的功能:
//adds the pre-encoded query parameter to this URL's query string
addEncodedQueryParameter(String encodedName, String encodedValue)
//encodes the query parameter using UTF-8 and adds it to this URL's query string
addQueryParameter(String name, String value)
more detailed: https://stackoverflow.com/a/32146909/5247331
回答by Louis CAD
Here's my interceptor
这是我的拦截器
private static class AuthInterceptor implements Interceptor {
private String mApiKey;
public AuthInterceptor(String apiKey) {
mApiKey = apiKey;
}
@Override
public Response intercept(Chain chain) throws IOException {
HttpUrl url = chain.request().httpUrl()
.newBuilder()
.addQueryParameter("api_key", mApiKey)
.build();
Request request = chain.request().newBuilder().url(url).build();
return chain.proceed(request);
}
}
回答by Miha_x64
You can create a newBuilder from existing HttoUrl and add query parameters there. Sample interceptor code:
您可以从现有的 HttoUrl 创建一个 newBuilder 并在那里添加查询参数。示例拦截器代码:
Request req = it.request()
return chain.proceed(
req.newBuilder()
.url(
req.url().newBuilder()
.addQueryParameter("v", "5.60")
.build());
.build());
回答by Yun CHEN
For okhttp3:
对于 okhttp3:
private static final OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
public static void get(String url, Map<String,String>params, Callback responseCallback) {
HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
if (params != null) {
for(Map.Entry<String, String> param : params.entrySet()) {
httpBuilder.addQueryParameter(param.getKey(),param.getValue());
}
}
Request request = new Request.Builder().url(httpBuilder.build()).build();
client.newCall(request).enqueue(responseCallback);
}
回答by marcode_ely
I finally did my code, hope the following code can help you guys. I build the URL first using
我终于完成了我的代码,希望下面的代码可以帮助你们。我首先使用
HttpUrl httpUrl = new HttpUrl.Builder()
HttpUrl httpUrl = new HttpUrl.Builder()
Then pass the URL to Request requesthttp
hope it helps .
然后传递 URL 以Request requesthttp
希望它有所帮助。
public class NetActions {
OkHttpClient client = new OkHttpClient();
public String getStudentById(String code) throws IOException, NullPointerException {
HttpUrl httpUrl = new HttpUrl.Builder()
.scheme("https")
.host("subdomain.apiweb.com")
.addPathSegment("api")
.addPathSegment("v1")
.addPathSegment("students")
.addPathSegment(code) // <- 8873 code passthru parameter on method
.addQueryParameter("auth_token", "71x23768234hgjwqguygqew")
// Each addPathSegment separated add a / symbol to the final url
// finally my Full URL is:
// https://subdomain.apiweb.com/api/v1/students/8873?auth_token=71x23768234hgjwqguygqew
.build();
System.out.println(httpUrl.toString());
Request requesthttp = new Request.Builder()
.addHeader("accept", "application/json")
.url(httpUrl) // <- Finally put httpUrl in here
.build();
Response response = client.newCall(requesthttp).execute();
return response.body().string();
}
}