添加查询参数以一个GET请求okhttp Android中参数、GET、Android、okhttp

2023-09-07 14:19:49 作者:独守空城待佳人

有没有办法来添加查询参数(参数1 = VAL1和放大器;参数2 = val2的)使用GET请求 okhttp Android中?

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

我要寻找一个API,而不是手动添加PARAMS在一个循环和转义值。

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

推荐答案

尝试 HttpUrl 类(在 okhttp 包)。

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

例如:

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