[英]Add query params to a GET request in okhttp in Android
Is there a way to add query params ( ?param1=val1¶m2=val2
) to a GET request using okhttp
in Android?有没有办法在 Android 中使用
okhttp
将查询参数( ?param1=val1¶m2=val2
)添加到 GET 请求中?
I am looking for an API and not manually adding the params in a loop and escaping the values.我正在寻找一个 API,而不是在循环中手动添加参数并转义这些值。
Try HttpUrl
class (in okhttp
package). 尝试
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 注意:如果已经存在具有此名称的名称/值对,则这些函数将删除它们,并且仅在添加此新对之后
Example: 例:
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("www.google.com")
.addPathSegment("search")
.addQueryParameter("q", "polar bears")
.build();
Say you already have a String url ready, just want to append the queries: 假设您已准备好String url,只想附加查询:
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 . 有关查询参数的详细信息,请参阅Vitaly的答案,或参阅文档 。
This is not possible with the current version of okhttp, there is no method provided that will handle this for you . 对于当前版本的okhttp, 这是不可能的 , 没有提供可以为您处理此问题的方法 。
However, Jesse Wilson , one of okhttp's developers, has stated that 然而,okhttp的开发人员之一Jesse Wilson 表示
We're adding a new HttpUrl class that can do this in the next release.
我们正在添加一个新的HttpUrl类,可以在下一个版本中执行此操作。
import android.net.Uri
var url = Uri.parse(urlWithoutQueryParams).buildUpon().appendQueryParameter("key","value").build().toString()
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
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()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.