Java stitching map into "parameter = value & parameter = value"

Source: Internet
Author: User

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"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.