12

Is there a way to add query params (?param1=val1&param2=val2) to a GET request using okhttp in Android?

I am looking for an API and not manually adding the params in a loop and escaping the values.

Wesley
  • 4,084
  • 6
  • 37
  • 60
dors
  • 5,802
  • 8
  • 45
  • 71

6 Answers6

14

Try HttpUrl class (in okhttp package).


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

Note: if there are already name/value pairs with this name, these functions will just add another pair


setEncodedQueryParameter(String encodedName, String encodedValue)

setQueryParameter(String name, String value)

Note: if there are already name/value pairs with this name, these functions will remove them and only after that add this new pair


Example:

HttpUrl url = new HttpUrl.Builder()
    .scheme("https")
    .host("www.google.com")
    .addPathSegment("search")
    .addQueryParameter("q", "polar bears")
    .build();
Vitaly Zinchenko
  • 4,871
  • 5
  • 36
  • 52
4

Use HttpUrl.

Say you already have a String url ready, just want to append the queries:

HttpUrl url = HttpUrl.parse("http://www.google.com/search").newBuilder()
   .addQueryParameter("q", "cat videos")
   .build();

For the details about query parameters, see Vitaly's answer, or refer to the documentation.

Jack
  • 5,354
  • 2
  • 29
  • 54
1

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

However, Jesse Wilson, one of okhttp's developers, has stated that

We're adding a new HttpUrl class that can do this in the next release.

Community
  • 1
  • 1
Tim
  • 41,901
  • 18
  • 127
  • 145
1
val url = "https://api.flutterwave.com/v3/transfers/fee".toHttpUrlOrNull()?.newBuilder()
            ?.addQueryParameter("amount", "100")
            ?.addQueryParameter("currency", curr)
            ?.build()

 val request = url?.let {
        okhttp3.Request.Builder()
            .header("Authorization", "Bearer ${HeaderBearerKey}")
            .header("Content-Type", "application/json")
            .url(it)
            .build()
    }
Timchang Wuyep
  • 629
  • 7
  • 10
0
import android.net.Uri
var url = Uri.parse(urlWithoutQueryParams).buildUpon().appendQueryParameter("key","value").build().toString()
Jack Wang
  • 462
  • 7
  • 17
0

Example:

HttpUrl url = new HttpUrl.Builder()
    .scheme("https")
    .host("www.google.com")
    .addPathSegment("search")
    .addQueryParameter("q", "polar bears")
    .build();
System.out.println(url);

output:

https://www.google.com/search?q=polar%20bears
Shahrad Elahi
  • 774
  • 12
  • 22