57

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!

1

9 Answers 9

83

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

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().url()
                .newBuilder()
                .addQueryParameter("api_key", mApiKey)
                .build();
        Request request = chain.request().newBuilder().url(url).build();
        return chain.proceed(request);
    }
}
0
17

I finally did my code, hope the following code can help you guys. I build the URL first using

HttpUrl httpUrl = new HttpUrl.Builder()

Then pass the URL to Request requesthttp hope it helps .

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

As mentioned in the other answer, okhttp v2.4 offers new functionality that does make this possible.

See http://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/HttpUrl.Builder.html#addQueryParameter-java.lang.String-java.lang.String-



This is not possible with the current version of okhttp, there is no method provided that will handle this for you.

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.

enter image description here

As you can see, the Request.Builder can take either a String or an 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?

2
  • 2
    We're adding a new HttpUrl class that can do this in the next release. May 9, 2015 at 18:26
  • @JesseWilson that is a nice improvemend :-)
    – Tim
    May 9, 2015 at 18:27
5

As of right now (okhttp 2.4), HttpUrl.Builder now has methods addQueryParameter and addEncodedQueryParameter.

1

You can create a newBuilder from existing HttoUrl and add query parameters there. Sample interceptor code:

    Request req = it.request()
    return chain.proceed(
        req.newBuilder()
            .url(
                req.url().newBuilder()
                .addQueryParameter("v", "5.60")
                .build());
    .build());
0

Use HttpUrl class's functions:

//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

0

One-line example:

assert HttpUrl.parse("https://httpbin.org/get")
        .newBuilder()
        .addQueryParameter("hello", "world")
        .build()
        .equals("https://httpbin.org/get?hello=world");
0

Beased on https://www.digitalocean.com/community/tutorials/okhttp-android-example-tutorial

HttpUrl.Builder urlBuilder = HttpUrl.parse("https://example.COM/
/** we are creating a url*/
THE_API_PATH").newBuilder();

 /**Adding parameters*/
urlBuilder.addQueryParameter("website", "www.example.com");
urlBuilder.addQueryParameter("tutorials", "android");

/** building url and converting it to string */
String url = urlBuilder.build().toString();


/** creating request so we could give it to OkHTTP */
Request request = new Request.Builder()
                 .url(url)
                 .build();


OkHttpClient client = new OkHttpClient();
 client.newCall(request).enqueue(new Callback() {
  @Override
  public void onFailure(Call call, IOException e) {
    Log.i("HTTP " ,  " " +  e.toString() );
    call.cancel();
  }

  @Override
  public void onResponse(Call call, Response response) throws IOException {

    final String myResponse = response.body().string();

    MainActivity.this.runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Log.i("HTTP " , "Response it's :" + myResponse );
       /** this it's your Response to String 
        if you are using json , convert your string .
         better to not do that in main thread*/
      }
    });

  }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.