Java stitching map into "parameter = value & parameter = value"
Stitching a map's key-value pairs into a form of "parameter = value & parameter = value", or "username=angusbao&password=123456", is a convenient way to pass, especially when the interface is called, which is more commonly used, such as the Get method of HTTP request, how to solve it with Java?
The code is as follows:
/**
* Sort all the elements of the array and use the "&" character to stitch into a string according to the "parameter = parameter value" pattern
* @param params need to sort and participate in the character stitching parameter group
* @return string after stitching
* @throws unsupportedencodingexception
*/
public static String Createlinkstringbyget (map<string, string> params) throws Unsupportedencodingexception {
list<string> keys = new arraylist<string> (Params.keyset ());
Collections.sort (keys);
String prestr = "";
for (int i = 0; i < keys.size (); i++) {
String key = Keys.get (i);
String value = Params.get (key);
Value = Urlencoder.encode (value, "UTF-8");
if (i = = Keys.size ()-1) {//stitching, excluding last & character
PRESTR = prestr + key + "=" + value;
} else {
PRESTR = prestr + key + "=" + Value + "&";
}
}
return prestr;
}
public static void Main (string[] args) throws Unsupportedencodingexception {
map<string,string> map= new hashmap<string,string> ();
Map.put ("1", "Hello");
Map.put ("2", "World");
SYSTEM.OUT.PRINTLN (Createlinkstringbyget (map));
}
The final result is: 1=hello&2=world
Java stitching map into "parameter = value & parameter = value"