Java tutorial
//package com.java2s; /* Copyright 2014 MITRE Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; public class Main { /** * Given an un-encoded URI query string, this will return a normalized, properly encoded URI query string. * <b>Important:</b> This method uses java's URLEncoder, which returns things that are * application/x-www-form-urlencoded, instead of things that are properly octet-esacped as the URI spec * requires. As a result, some substitutions are made to properly translate space characters to meet the * URI spec. * @param queryString * @return */ private static String normalizeQueryString(String queryString) throws UnsupportedEncodingException { if ("".equals(queryString) || queryString == null) return queryString; String[] pieces = queryString.split("&"); HashMap<String, String> kvp = new HashMap<String, String>(); StringBuffer builder = new StringBuffer(""); for (int x = 0; x < pieces.length; x++) { String[] bs = pieces[x].split("=", 2); bs[0] = URLEncoder.encode(bs[0], "UTF-8"); if (bs.length == 1) kvp.put(bs[0], null); else { kvp.put(bs[0], URLEncoder.encode(bs[1], "UTF-8").replaceAll("\\+", "%20")); } } // Sort the keys alphabetically, ignoring case. ArrayList<String> keys = new ArrayList<String>(kvp.keySet()); Collections.sort(keys, new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); // With the alphabetic list of parameter names, re-build the query string. for (int x = 0; x < keys.size(); x++) { // Some parameters have no value, and are simply present. If so, we put null in kvp, // and we just put the parameter name, no "=value". if (kvp.get(keys.get(x)) == null) builder.append(keys.get(x)); else builder.append(keys.get(x) + "=" + kvp.get(keys.get(x))); if (x < (keys.size() - 1)) builder.append("&"); } return builder.toString(); } }