Java tutorial
//package com.java2s; //License from project: Apache License import java.util.Map; public class Main { /** * Replaces template parameters in the given url * @param queryBuilder The query string builder to replace the template parameters * @param parameters The parameters to replace in the url */ public static void appendUrlWithTemplateParameters(StringBuilder queryBuilder, Map<String, Object> parameters) { //perform parameter validation if (null == queryBuilder) throw new IllegalArgumentException("Given value for parameter \"queryBuilder\" is invalid."); if (null == parameters) return; //iterate and append parameters for (Map.Entry<String, Object> pair : parameters.entrySet()) { String replaceValue = ""; //load parameter value if (null != pair.getValue()) replaceValue = pair.getValue().toString(); //find the template parameter and replace it with its value replaceAll(queryBuilder, "{" + pair.getKey() + "}", replaceValue); } } /** * Replaces all occurrences of the given string in the string builder * @param stringBuilder The string builder to update with replaced strings * @param toReplace The string to replace in the string builder * @param replaceWith The string to replace with*/ public static void replaceAll(StringBuilder stringBuilder, String toReplace, String replaceWith) { int index = stringBuilder.indexOf(toReplace); while (index != -1) { stringBuilder.replace(index, index + toReplace.length(), replaceWith); index += replaceWith.length(); // Move to the end of the replacement index = stringBuilder.indexOf(toReplace, index); } } }