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

Jerikc XIONG picture Jerikc XIONG · May 9, 2015 · Viewed 68.6k times · Source

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!

Answer

Yun CHEN picture Yun CHEN · Mar 26, 2017

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