Java URI Create addQueryParametersToUri(URI uri, Map parameters)

Here you can find the source of addQueryParametersToUri(URI uri, Map parameters)

Description

add Query Parameters To Uri

License

Apache License

Declaration

public static URI addQueryParametersToUri(URI uri, Map<String, Object> parameters) throws URISyntaxException 

Method Source Code


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

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import static com.google.common.base.Strings.isNullOrEmpty;

public class Main {
    private static final String FIRST_PARAMETER_CONCATENATOR = "?";
    private static final String PARAMETERS_ASSIGNMENT = "=";
    private static final String SECOND_AND_LATER_CONCATENATOR = "&";

    public static URI addQueryParametersToUri(URI uri, Map<String, Object> parameters) throws URISyntaxException {
        StringBuilder urlParametersBuilder = new StringBuilder();
        if (uri == null) {
            throw new IllegalArgumentException("Define URL before URL parameters");
        }//from   w ww . j a  v a2  s .c  o  m
        urlParametersBuilder.append(uri.toString());
        String concatenator = FIRST_PARAMETER_CONCATENATOR;
        for (String paramName : parameters.keySet()) {
            validateParameters(paramName);
            urlParametersBuilder.append(concatenator);
            urlParametersBuilder.append(paramName);
            Object parameterValue = parameters.get(paramName);

            if (doesContainValue(parameterValue)) {
                urlParametersBuilder.append(PARAMETERS_ASSIGNMENT);
                urlParametersBuilder.append(parameterValue.toString());
            }
            concatenator = SECOND_AND_LATER_CONCATENATOR;
        }
        return new URI(urlParametersBuilder.toString());
    }

    private static void validateParameters(String paramName) {
        if (isNullOrEmpty(paramName)) {
            throw new IllegalArgumentException("Parameter name should be not null or empty");
        }
    }

    private static boolean doesContainValue(Object value) {
        return value != null && !value.toString().equals("");
    }
}

Related

  1. addParameter(String name, String value, StringBuilder uri)
  2. addParameters(Map parameters, StringBuilder uri)
  3. addParams(final Map params, final StringBuilder uri)
  4. addParams(URI uri, Map> params, Set overridenParams)
  5. addQueryParamsToUri(String uri, Map queryParams)
  6. addQueryString(final URI uri, final String queryString)
  7. convertToURI(String uriOrPath)
  8. convertToURI(String uriString, Map aliasMap)