Here you can find the source of buildUrl(String baseUrl, Map queryParams, String anchor)
Parameter | Description |
---|---|
baseUrl | base URL |
queryParams | query parameters |
anchor | anchor |
public static String buildUrl(String baseUrl, Map queryParams, String anchor)
//package com.java2s; //License from project: Open Source License import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Iterator; import java.util.Map; public class Main { public static final String QUERY_CHAR = "?"; public static final String ANCHOR_CHAR = "#"; public static final String PARAM_SEPARATOR = "&"; public static final String PARAM_EQUALS = "="; /**/*from ww w. j a v a 2s . c o m*/ * UTF-8 encode constants. */ public static final String UTF_8_ENCODING = "UTF-8"; /** * Builds an URL. * * @param baseUrl * base URL * @param queryParams * query parameters * @param anchor * anchor * @return URL */ public static String buildUrl(String baseUrl, Map queryParams, String anchor) { // Save the URL String StringBuffer url = new StringBuffer(); url.append(baseUrl); if (queryParams != null && !queryParams.isEmpty()) { url.append(QUERY_CHAR); url.append(makeUriString(queryParams)); } if (anchor != null) { url.append(ANCHOR_CHAR); url.append(anchor); } return url.toString(); } /** * Makes an URI string based on the given parameters. * * @param parameters * map of parameters to values (must be String) * @return URI string */ public static String makeUriString(Map parameters) { StringBuffer output = new StringBuffer(); for (Iterator i = parameters.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); Object value = entry.getValue(); output.append(urlParamValueEncode(entry.getKey())); if (value != null) { output.append(PARAM_EQUALS); output.append(urlParamValueEncode(value)); } if (i.hasNext()) { output.append(PARAM_SEPARATOR); } } return output.toString(); } /** * Encode the url parameter value * * @param s * string to encode * @return */ public static String urlParamValueEncode(String s) { if (s != null) { try { return URLEncoder.encode(s, UTF_8_ENCODING); } catch (UnsupportedEncodingException e) { } } return s; } /** * Encode the url parameter value * * @param plain * @return */ public static String urlParamValueEncode(Object value) { if (!(value instanceof String)) { value = value.toString(); } return urlParamValueEncode((String) value); } }