Java URL Create buildURL(URI base, Multimap params)

Here you can find the source of buildURL(URI base, Multimap params)

Description

build URL

License

Apache License

Declaration

public static String buildURL(URI base, Multimap<String, String> params) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Map;
import com.google.common.collect.Multimap;

public class Main {
    public static String buildURL(URI base, Multimap<String, String> params) {
        if (params.isEmpty()) {
            return base.toString();
        } else {//w  ww  .  j  a va 2s  . c o  m
            return base + "?" + buildQueryString(params);
        }
    }

    /**
     * Create a query string
     */
    private static String buildQueryString(Multimap<String, String> params) {
        StringBuilder bld = new StringBuilder();

        boolean afterFirst = false;
        for (Map.Entry<String, String> entry : params.entries()) {
            if (afterFirst)
                bld.append("&");
            else
                afterFirst = true;

            bld.append(urlEncode(entry.getKey()));
            bld.append("=");
            checkNotNull(entry.getValue(), format("query parameter[%s] has no value", entry.getKey()));
            bld.append(urlEncode(entry.getValue()));
        }

        return bld.toString();
    }

    /**
     * An interface to URLEncoder.encode() that isn't inane
     */
    public static String urlEncode(Object value) {
        try {
            return URLEncoder.encode(value.toString(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. buildURL(String url)
  2. buildURL(String url)
  3. buildUrl(String url, HashMap params)
  4. buildUrl(String URL, Map params)
  5. buildUrl(String urlPrefix, String urlSuffix)
  6. buildUrlPath(String baseUrl, String childUrl)
  7. buildUrlsList(final String domain, final String... paths)
  8. buildURLString(Iterable elements, String joiner)
  9. concatenate(URL server, String address)