如何将 ContentValue 值编码并附加到 URL

How to encode and append ContentValue values into an URL

早些时候,当 NameValuePairs 直接可用时,很容易使用以下方法编码和附加 URL 变量:

String UrlString = URLEncodedUtils.format(nameValuePairs, "utf-8");

但现在它们已被弃用,我开始使用 ContentValues 来存储名称-值对。

我想问的是,有没有一种简单直接的方法可以将 ContentValue 值编码并附加到 URL 中,就像 NameValuePairs 一样,否则该怎么做?

What I want to ask that is there an easy and straight way to encode and append ContentValue values into an URL like it was possible with NameValuePairs or else how to do it?

如果您指的是查询参数,最好看看 Uri. In particular, its Builder 提供了各种方法来设置或附加路径段、查询参数(预编码或未编码)以及像。静态 Uri.encode() 助手也支持编码值。

话虽如此,如果您需要对 URLEncodedUtils 提供的格式设置选项进行简单的替代,获取其源代码并使其与 ContentValues 兼容将非常简单(或者就此而言 Map<String, Object>,因为 ContentValues 只不过是围绕它的薄包装)。

我为此设置了一个快速(未经测试)gist。随意使用它作为起点,并且 - 无论如何 - 修复我可能犯的任何错误。

如果您要通过字符串构建 URL,请按照以下说明进行操作。

String urlEncoded = "http://google.com/search?q=" + Uri.encode(查询);