Jer*_*ONG 31 java http-get query-parameters okhttp
我使用的是最新的okhttp版本:okhttp-2.3.0.jar
如何在java中的okhttp中向GET请求添加查询参数?
我发现了一个关于android 的相关问题,但这里没有答案!
Yun*_*HEN 38
对于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);
}
Run Code Online (Sandbox Code Playgroud)
Lou*_*CAD 19
这是我的拦截器
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);
}
}
Run Code Online (Sandbox Code Playgroud)
Tim*_*Tim 10
正如在另一个答案中所提到的,okhttp v2.4提供了新功能,可以实现这一点.
对于当前版本的okhttp,这是不可能的,没有提供可以为您处理此问题的方法.
接下来最好的事情是使用自己包含的查询构建url字符串或URL对象(找到java.net.URL),并将其传递给okhttp的请求构建器.

如您所见,Request.Builder可以使用String或URL.
有关如何构建URL的示例可以在Java中组合URL或URI的惯用方法中找到?
我终于完成了我的代码,希望以下代码可以帮助你们.我首先使用构建URL
HttpUrl httpUrl = new HttpUrl.Builder()
然后传递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();
}
}
Run Code Online (Sandbox Code Playgroud)