How to add query parameters to a HTTP GET request by OkHttp?

I am using the latest okhttp version: okhttp-2.3.0.jar

How to add query parameters to GET request in okhttp in java ?

I found a related question about android, but no answer here!


Solution 1:

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

Solution 2:

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