如何通过 OkHttp 将查询参数添加到 HTTP GET 请求中?

2022-08-31 20:23:57

我使用的是最新的 okhttp 版本:okhttp-2.3.0.jar

如何在java中的okhttp中添加查询参数到GET请求中?

我发现了一个关于Android的相关问题,但这里没有答案!


答案 1

对于 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);
}

答案 2

这是我的拦截器

    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);
    }
}