[英]Generate a Get query string in Java
I want to generate a Get query string in java like so 我想像这样在Java中生成Get查询字符串
www.example.com/somethingToGet?key1=value&key2=value....
So my method has 2 parameters the base url(www.example.com/somethingToGet) is the first argument and the 2nd argument is a map data structure. 因此,我的方法有2个参数,基本url(www.example.com/somethingToGet)是第一个参数,第二个参数是map数据结构。 I want to iterate over the map and generate a string like so
我想遍历地图并生成一个像这样的字符串
key1=value&key2=value....
It shouldn't end with ampersand. 它不应该以“&”号结尾。 I don't want to use any built in functions, I want to know the logic how such strings are generated.
我不想使用任何内置函数,我想知道如何生成此类字符串的逻辑。
Something like this: 像这样:
public static String getQuery(String base, java.util.Map<String, String> map) {
StringBuilder str = new StringBuilder(base);
str.append('?');
boolean first = true;
for (java.util.Map.Entry<String, String> e : map.entrySet()) {
if (first)
first = false;
else
str.append('&');
str.append(e.getKey());
str.append('=');
str.append(e.getValue());
}
return str.toString();
}
You can also use the format method in URLEncoder class from the Apache HttpComponents library to create a query string. 您还可以使用Apache HttpComponents库中URLEncoder类中的format方法来创建查询字符串。 As per the documentation it
根据文档
Returns a String that is suitable for use as an application/x-www-form-urlencoded list of parameters in an HTTP PUT or HTTP POST.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.