是否有一个Java方法将参数集合编码为URL查询组件?

时间:2009-09-10 14:47:31

标签: java http url encoding

是否有广泛使用的Java库可以执行dojo.objectToQuery()之类的操作?例如。 (假设使用HttpCore的HttpParams对象,但任何键值映射都可以):

HttpParams params = new BasicHttpParams()
    .setParameter("foo", "bar")
    .setParameter("thud", "grunt");
UnknownLibrary.toQueryString(params);

应该产生“foo = bar& thud = grunt”。

我知道写起来并不难,但似乎应该已经写好了。我找不到它。

5 个答案:

答案 0 :(得分:11)

为什么重新发明轮子? Apache HttpClient有URLEncodedUtils:

   List<BasicNameValuePair> params = Arrays.asList(new BasicNameValuePair("\\%^ &=@#:", "\\%^ &=@#:"));
   String query = URLEncodedUtils.format(params, "UTF-8");

答案 1 :(得分:5)

你真的不需要一个库。我在HttpCore中找不到一个,所以我写了这样的东西,

public String toString() {

    StringBuilder sb = new StringBuilder(baseUrl);

    char separator;

    if (baseUrl.indexOf('?') > 0)
        separator = '&';
    else
        separator = '?';

    for (Parameter p : parameters) {
        sb.append(separator);
        try {
            sb.append(URLEncoder.encode(p.name, "UTF-8"));
            if (p.value != null) {
                sb.append('=');
                sb.append(URLEncoder.encode(p.value, "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            // Not really possible, throw unchecked exception
            throw new IllegalStateException("No UTF-8");
        }

        separator = '&';
    }

    return sb.toString();
}

答案 2 :(得分:5)

我最终写了自己的。它可以被称为

URIUtils.withQuery(uri, "param1", "value1", "param2", "value2");

这不是那么糟糕。

/**
 * Concatenates <code>uri</code> with a query string generated from
 * <code>params</code>.
 *
 * @param uri the base URI
 * @param params a <code>Map</code> of key/value pairs
 * @return a new <code>URI</code>
 */

public static URI withQuery(URI uri, Map<String, String> params) {
    StringBuilder query = new StringBuilder();
    char separator = '?';
    for (Entry<String, String> param : params.entrySet()) {
        query.append(separator);
        separator = '&';
        try {
            query.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            if (!StringUtils.isEmpty(param.getValue())) {
                query.append('=');
                query.append(URLEncoder.encode(param.getValue(), "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    return URI.create(uri.toString() + query.toString());
}

/**
 * Concatenates <code>uri</code> with a query string generated from
 * <code>params</code>.  The members of <code>params</code> will be
 * interpreted as {key1, val1, key2, val2}.  Empty values can be given
 * as <code>""</code> or <code>null</code>.
 *
 * @param uri the base URI
 * @param params the key/value pairs in sequence
 * @return a new <code>URI</code>
 */
public static URI withQuery(URI uri, String... params) {
    Map<String, String> map = new LinkedHashMap<String, String>();
    for (int i = 0; i < params.length; i += 2) {
        String key = params[i];
        String val = i + 1 < params.length ? params[i + 1] : "";
        map.put(key, val);
    }
    return withQuery(uri, map);
}

答案 3 :(得分:1)

如果你有JAX-RS,那就是javax.ws.rs.core.UriBuilder;除此之外,您应该首先了解URLEncoder和URLDecoder,它们至少会编码参数列表的各个部分。

答案 4 :(得分:0)

有很多库可以帮助你构建URI(不要重新发明轮子)。这是一个让你入门的人:

org.springframework:spring-web:4.2.5.RELEASE

start_urls

另请参阅: GIST > URI Builder Tests