diff --git a/api/src/main/java/io/grpc/QueryParams.java b/api/src/main/java/io/grpc/QueryParams.java new file mode 100644 index 00000000000..8bc8723df53 --- /dev/null +++ b/api/src/main/java/io/grpc/QueryParams.java @@ -0,0 +1,272 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.base.Splitter; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import javax.annotation.Nullable; + +/** + * A parser and mutable container class for {@code application/x-www-form-urlencoded}-style URL + * parameters as conceived by + * RFC 1866 Section 8.2.1. + * + *

For example, a URI like {@code "http://who?name=John+Doe&role=admin&role=user&active"} has: + * + *

+ * + *

Instances are not safe for concurrent access by multiple threads. + */ +@Internal +public final class QueryParams { + + private static final String UTF_8 = "UTF-8"; + private final List entries = new ArrayList<>(); + + /** Creates a new, empty {@code QueryParameters} instance. */ + public QueryParams() {} + + /** + * Parses a raw query string into a {@code QueryParameters} instance. + * + *

The input is split on {@code '&'} and each parameter is parsed as either a key/value pair + * (if it contains an equals sign) or a "lone" key (if it does not). + * + * @param rawQuery the raw query component to parse, must not be null + * @return a new {@code QueryParameters} instance containing the parsed parameters + */ + public static QueryParams parseRawQueryString(String rawQuery) { + checkNotNull(rawQuery, "rawQuery"); + QueryParams params = new QueryParams(); + if (!rawQuery.isEmpty()) { + for (String part : Splitter.on('&').split(rawQuery)) { + int equalsIndex = part.indexOf('='); + if (equalsIndex == -1) { + params.add(Entry.forRawLoneKey(part)); + } else { + String rawKey = part.substring(0, equalsIndex); + String rawValue = part.substring(equalsIndex + 1); + params.add(Entry.forRawKeyValue(rawKey, rawValue)); + } + } + } + return params; + } + + /** + * Returns the last parameter in the parameters list having the specified key. + * + * @param key the key to search for (non-encoded) + * @return the matching {@link Entry}, or {@code null} if no match is found + */ + @Nullable + public Entry getLast(String key) { + checkNotNull(key, "key"); + for (int i = entries.size() - 1; i >= 0; --i) { + Entry entry = entries.get(i); + if (entry.getKey().equals(key)) { + return entry; + } + } + return null; + } + + /** + * Appends 'entry' to the list of query parameters. + * + * @param entry the entry to add + */ + public void add(Entry entry) { + entries.add(checkNotNull(entry, "entry")); + } + + /** + * Removes all entries equal to the specified entry. + * + *

Two entries are considered equal if they have the same key and value *after* any URL + * decoding has been performed. + * + * @param entry the entry to remove, must not be null + * @return the number of entries removed + */ + public int removeAll(Entry entry) { + checkNotNull(entry, "entry"); + int removed = 0; + Iterator it = entries.iterator(); + while (it.hasNext()) { + if (it.next().equals(entry)) { + it.remove(); + removed++; + } + } + return removed; + } + + /** + * Returns the "raw" query string representation of these parameters, suitable for passing to the + * {@link io.grpc.Uri.Builder#setRawQuery} method. + * + * @return the raw query string + */ + public String toRawQueryString() { + StringBuilder resultBuilder = new StringBuilder(); + boolean first = true; + for (Entry entry : entries) { + if (!first) { + resultBuilder.append('&'); + } + entry.appendToRawQueryStringBuilder(resultBuilder); + first = false; + } + return resultBuilder.toString(); + } + + /** Returns true if and only if there are zero entries in this collection. */ + public boolean isEmpty() { + return entries.isEmpty(); + } + + @Override + public String toString() { + return toRawQueryString(); + } + + /** A single query parameter entry. */ + public static final class Entry { + private final String rawKey; + @Nullable private final String rawValue; + private final String key; + @Nullable private final String value; + + private Entry(String rawKey, @Nullable String rawValue, String key, @Nullable String value) { + this.rawKey = checkNotNull(rawKey, "rawKey"); + this.rawValue = rawValue; + this.key = checkNotNull(key, "key"); + this.value = value; + } + + /** + * Returns the key. + * + *

Any characters that needed URL encoding have already been decoded. + */ + public String getKey() { + return key; + } + + /** + * Returns the value, or {@code null} if this is a "lone" key. + * + *

Any characters that needed URL encoding have already been decoded. + */ + @Nullable + public String getValue() { + return value; + } + + /** + * Creates a new key/value pair entry. + * + *

Both key and value can contain any character. They will be URL encoded for you later, if + * necessary. + */ + public static Entry forKeyValue(String key, String value) { + checkNotNull(key, "key"); + checkNotNull(value, "value"); + return new Entry(encode(key), encode(value), key, value); + } + + /** + * Creates a new query parameter with a "lone" key. + * + *

'key' can contain any character. It will be URL encoded for you later, as necessary. + * + * @param key the decoded key, must not be null + * @return a new {@code Entry} + */ + public static Entry forLoneKey(String key) { + checkNotNull(key, "key"); + return new Entry(encode(key), null, key, null); + } + + static Entry forRawKeyValue(String rawKey, String rawValue) { + checkNotNull(rawKey, "rawKey"); + checkNotNull(rawValue, "rawValue"); + return new Entry(rawKey, rawValue, decode(rawKey), decode(rawValue)); + } + + static Entry forRawLoneKey(String rawKey) { + checkNotNull(rawKey, "rawKey"); + return new Entry(rawKey, null, decode(rawKey), null); + } + + void appendToRawQueryStringBuilder(StringBuilder sb) { + sb.append(rawKey); + if (rawValue != null) { + sb.append('=').append(rawValue); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Entry)) { + return false; + } + Entry entry = (Entry) o; + return Objects.equals(key, entry.key) && Objects.equals(value, entry.value); + } + + @Override + public int hashCode() { + return Objects.hash(key, value); + } + } + + private static String decode(String s) { + try { + // TODO: Use URLDecoder.decode(String, Charset) when available + return URLDecoder.decode(s, UTF_8); + } catch (UnsupportedEncodingException impossible) { + throw new AssertionError("UTF-8 is not supported", impossible); + } + } + + private static String encode(String s) { + try { + // TODO: Use URLEncoder.encode(String, Charset) when available + return URLEncoder.encode(s, UTF_8); + } catch (UnsupportedEncodingException impossible) { + throw new AssertionError("UTF-8 is not supported", impossible); + } + } +} diff --git a/api/src/main/java/io/grpc/Uri.java b/api/src/main/java/io/grpc/Uri.java index 9f8a5a87848..1c18fd70ed1 100644 --- a/api/src/main/java/io/grpc/Uri.java +++ b/api/src/main/java/io/grpc/Uri.java @@ -546,24 +546,18 @@ public String getRawPath() { return path; } - /** - * Returns the percent-decoded "query" component of this URI, or null if not present. - * - *

NB: This method assumes the query was encoded as UTF-8, although RFC 3986 doesn't specify an - * encoding. - * - *

Decoding errors are indicated by a {@code '\u005CuFFFD'} unicode replacement character in - * the output. Callers who want to detect and handle errors in some other way should call {@link - * #getRawQuery()}, {@link #percentDecode(CharSequence)}, then decode the bytes for themselves. - */ - @Nullable - public String getQuery() { - return percentDecodeAssumedUtf8(query); - } - /** * Returns the query component of this URI in its originally parsed, possibly percent-encoded - * form, without any leading '?' character. + * form, without any leading '?' character, or null if not present. + * + *

The query component can only be read in its raw form. That’s because virtually everyone uses + * query as a container for structured data, with some additional layer of encoding not present in + * RFC-3986. Like 'application/x-www-form-urlencoded', which encodes key/value pairs like so: + * ?k1=v1&k2=v+2. The encoding of these containers always has characters that take on + * a special delimiter meaning when not percent-encoded and a literal meaning when they are (like + * '&', '=' and '+' above). Since it matters whether a character was percent encoded or not, + * offering a '#getQuery()' method that percent-decodes everything like we do for other components + * would be error-prone. */ @Nullable public String getRawQuery() { @@ -776,10 +770,20 @@ public Builder setRawPath(String path) { } /** - * Specifies the query component of the new URI (not including the leading '?'). + * Specifies the query component of the new URI, possibly percent-encoded, exactly as it will + * appear in the string form of the built URI. * - *

Query can contain any string of codepoints. Codepoints that can't be encoded literally - * will be percent-encoded for you as UTF-8. + *

'query' must only contain codepoints from RFC 3986's "query" character class. Any other + * characters must be percent-encoded using UTF-8. Do not include the leading '?' delimiter. + * + *

The query component can only be provided in its raw form. That’s because virtually + * everyone uses query as a container for structured data, with some additional layer of + * encoding not present in RFC-3986. Like 'application/x-www-form-urlencoded', which encodes + * key/ value pairs like so: ?k1=v1&k2=v+2. The encoding of these containers always + * has characters that take on a special delimiter meaning when not percent-encoded and a + * literal meaning when they are (like '&', '=' and '+' above). Since 'query' must have already + * been carefully percent-encoded externally, a '#setQuery(String)' method that percent-encodes + * an assumed-cooked string would be error-prone. * *

This field is optional. * @@ -787,14 +791,10 @@ public Builder setRawPath(String path) { * @return this, for fluent building */ @CanIgnoreReturnValue - public Builder setQuery(@Nullable String query) { - this.query = percentEncode(query, queryChars); - return this; - } - - @CanIgnoreReturnValue - Builder setRawQuery(String query) { - checkPercentEncodedArg(query, "query", queryChars); + public Builder setRawQuery(@Nullable String query) { + if (query != null) { + checkPercentEncodedArg(query, "query", queryChars); + } this.query = query; return this; } diff --git a/api/src/test/java/io/grpc/QueryParamsTest.java b/api/src/test/java/io/grpc/QueryParamsTest.java new file mode 100644 index 00000000000..92ef6a27a1c --- /dev/null +++ b/api/src/test/java/io/grpc/QueryParamsTest.java @@ -0,0 +1,188 @@ +/* + * Copyright 2026 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import io.grpc.QueryParams.Entry; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link QueryParams}. */ +@RunWith(JUnit4.class) +public class QueryParamsTest { + + @Test + public void emptyInstance() { + QueryParams params = new QueryParams(); + assertTrue(params.isEmpty()); + assertEquals("", params.toRawQueryString()); + assertEquals("", params.toString()); + } + + @Test + public void parseEmptyString() { + QueryParams params = QueryParams.parseRawQueryString(""); + assertEquals("", params.toRawQueryString()); + assertTrue(params.isEmpty()); + } + + @Test + public void parseNormalPairs() { + QueryParams params = QueryParams.parseRawQueryString("a=b&c=d"); + assertEquals("a=b&c=d", params.toRawQueryString()); + + QueryParams.Entry a = params.getLast("a"); + assertEquals("a", a.getKey()); + assertEquals("b", a.getValue()); + + QueryParams.Entry c = params.getLast("c"); + assertEquals("c", c.getKey()); + assertEquals("d", c.getValue()); + } + + @Test + public void parseLoneKey() { + QueryParams params = QueryParams.parseRawQueryString("a&b"); + assertEquals("a&b", params.toRawQueryString()); + + QueryParams.Entry a = params.getLast("a"); + assertEquals("a", a.getKey()); + assertNull(a.getValue()); + + QueryParams.Entry b = params.getLast("b"); + assertEquals("b", b.getKey()); + assertNull(b.getValue()); + } + + @Test + public void parseEmptyKeysAndValues() { + QueryParams params = QueryParams.parseRawQueryString("=&="); + assertEquals("=&=", params.toRawQueryString()); + + QueryParams.Entry first = params.getLast(""); + // getLast returns the LAST one + assertEquals("", first.getKey()); + assertEquals("", first.getValue()); + } + + @Test + public void roundTripPreservesEncoding() { + // Spaces as + + QueryParams params1 = QueryParams.parseRawQueryString("a+b=c+d"); + assertEquals("a+b=c+d", params1.toRawQueryString()); + assertEquals("a b", params1.getLast("a b").getKey()); + assertEquals("c d", params1.getLast("a b").getValue()); + + // Spaces as %20 + QueryParams params2 = QueryParams.parseRawQueryString("a%20b=c%20d"); + assertEquals("a%20b=c%20d", params2.toRawQueryString()); + assertEquals("a b", params2.getLast("a b").getKey()); + assertEquals("c d", params2.getLast("a b").getValue()); + + // Case of percent encoding + QueryParams params3 = QueryParams.parseRawQueryString("a=%4A"); + assertEquals("a=%4A", params3.toRawQueryString()); + assertEquals("J", params3.getLast("a").getValue()); + + QueryParams params4 = QueryParams.parseRawQueryString("a=%4a"); + assertEquals("a=%4a", params4.toRawQueryString()); + assertEquals("J", params4.getLast("a").getValue()); + } + + @Test + public void addMethod() { + QueryParams params = new QueryParams(); + params.add(QueryParams.Entry.forKeyValue("a b", "c d")); + params.add(QueryParams.Entry.forLoneKey("e f")); + + // URLEncoder encodes spaces as + + assertEquals("a+b=c+d&e+f", params.toRawQueryString()); + } + + @Test + public void removeAllMethod() { + QueryParams params = QueryParams.parseRawQueryString("a=b&c=d&a=b&a=c"); + + QueryParams.Entry toRemove = QueryParams.Entry.forKeyValue("a", "b"); + int removed = params.removeAll(toRemove); + + assertEquals(2, removed); + assertEquals("c=d&a=c", params.toRawQueryString()); + } + + @Test + public void removeAllLoneKey() { + QueryParams params = QueryParams.parseRawQueryString("a&b&a&a=b"); + + QueryParams.Entry toRemove = QueryParams.Entry.forLoneKey("a"); + int removed = params.removeAll(toRemove); + + assertEquals(2, removed); + assertEquals("b&a=b", params.toRawQueryString()); + } + + @Test + public void parseInvalidEncodingThrows() { + assertThrows(IllegalArgumentException.class, () -> QueryParams.parseRawQueryString("a=%GH")); + } + + @Test + public void uriIntegration() { + QueryParams params = new QueryParams(); + params.add(Entry.forKeyValue("a", "b")); + params.add(Entry.forKeyValue("c", "d")); + + Uri uri = + Uri.newBuilder() + .setScheme("http") + .setHost("example.com") + .setRawQuery(params.toRawQueryString()) + .build(); + + assertEquals("http://example.com?a=b&c=d", uri.toString()); + assertEquals("a=b&c=d", uri.getRawQuery()); + } + + @Test + public void keysAndValuesWithCharactersNeedingUrlEncoding() { + QueryParams params = new QueryParams(); + params.add(Entry.forKeyValue("a=b", "c&d")); + params.add(Entry.forKeyValue("e+f", "g h")); + + assertEquals("a%3Db=c%26d&e%2Bf=g+h", params.toRawQueryString()); + + QueryParams roundTripped = QueryParams.parseRawQueryString(params.toRawQueryString()); + assertEquals("c&d", roundTripped.getLast("a=b").getValue()); + assertEquals("g h", roundTripped.getLast("e+f").getValue()); + } + + @Test + public void keysAndValuesWithCodePointsOutsideAsciiRange() { + QueryParams params = new QueryParams(); + params.add(Entry.forKeyValue("€", "𐐷")); + + assertEquals("%E2%82%AC=%F0%90%90%B7", params.toRawQueryString()); + + QueryParams roundTripped = QueryParams.parseRawQueryString(params.toRawQueryString()); + assertEquals("𐐷", roundTripped.getLast("€").getValue()); + } +} diff --git a/api/src/test/java/io/grpc/UriTest.java b/api/src/test/java/io/grpc/UriTest.java index a1bd550696f..71ec1749b7d 100644 --- a/api/src/test/java/io/grpc/UriTest.java +++ b/api/src/test/java/io/grpc/UriTest.java @@ -42,7 +42,7 @@ public void parse_allComponents() throws URISyntaxException { assertThat(uri.getPort()).isEqualTo(443); assertThat(uri.getRawPort()).isEqualTo("0443"); assertThat(uri.getPath()).isEqualTo("/path"); - assertThat(uri.getQuery()).isEqualTo("query"); + assertThat(uri.getRawQuery()).isEqualTo("query"); assertThat(uri.getFragment()).isEqualTo("fragment"); assertThat(uri.toString()).isEqualTo("scheme://user@host:0443/path?query#fragment"); assertThat(uri.isAbsolute()).isFalse(); // Has a fragment. @@ -56,7 +56,7 @@ public void parse_noAuthority() throws URISyntaxException { assertThat(uri.getScheme()).isEqualTo("scheme"); assertThat(uri.getAuthority()).isNull(); assertThat(uri.getPath()).isEqualTo("/path"); - assertThat(uri.getQuery()).isEqualTo("query"); + assertThat(uri.getRawQuery()).isEqualTo("query"); assertThat(uri.getFragment()).isEqualTo("fragment"); assertThat(uri.toString()).isEqualTo("scheme:/path?query#fragment"); assertThat(uri.isAbsolute()).isFalse(); // Has a fragment. @@ -102,7 +102,7 @@ public void parse_noQuery() throws URISyntaxException { assertThat(uri.getScheme()).isEqualTo("scheme"); assertThat(uri.getAuthority()).isEqualTo("authority"); assertThat(uri.getPath()).isEqualTo("/path"); - assertThat(uri.getQuery()).isNull(); + assertThat(uri.getRawQuery()).isNull(); assertThat(uri.getFragment()).isEqualTo("fragment"); assertThat(uri.toString()).isEqualTo("scheme://authority/path#fragment"); } @@ -113,7 +113,7 @@ public void parse_noFragment() throws URISyntaxException { assertThat(uri.getScheme()).isEqualTo("scheme"); assertThat(uri.getAuthority()).isEqualTo("authority"); assertThat(uri.getPath()).isEqualTo("/path"); - assertThat(uri.getQuery()).isEqualTo("query"); + assertThat(uri.getRawQuery()).isEqualTo("query"); assertThat(uri.getFragment()).isNull(); assertThat(uri.toString()).isEqualTo("scheme://authority/path?query"); assertThat(uri.isAbsolute()).isTrue(); @@ -125,7 +125,7 @@ public void parse_emptyPathWithAuthority() throws URISyntaxException { assertThat(uri.getScheme()).isEqualTo("scheme"); assertThat(uri.getAuthority()).isEqualTo("authority"); assertThat(uri.getPath()).isEmpty(); - assertThat(uri.getQuery()).isNull(); + assertThat(uri.getRawQuery()).isNull(); assertThat(uri.getFragment()).isNull(); assertThat(uri.toString()).isEqualTo("scheme://authority"); assertThat(uri.isAbsolute()).isTrue(); @@ -139,7 +139,7 @@ public void parse_rootless() throws URISyntaxException { assertThat(uri.getScheme()).isEqualTo("mailto"); assertThat(uri.getAuthority()).isNull(); assertThat(uri.getPath()).isEqualTo("ceo@company.com"); - assertThat(uri.getQuery()).isEqualTo("subject=raise"); + assertThat(uri.getRawQuery()).isEqualTo("subject=raise"); assertThat(uri.getFragment()).isNull(); assertThat(uri.toString()).isEqualTo("mailto:ceo@company.com?subject=raise"); assertThat(uri.isAbsolute()).isTrue(); @@ -153,7 +153,7 @@ public void parse_emptyPath() throws URISyntaxException { assertThat(uri.getScheme()).isEqualTo("scheme"); assertThat(uri.getAuthority()).isNull(); assertThat(uri.getPath()).isEmpty(); - assertThat(uri.getQuery()).isNull(); + assertThat(uri.getRawQuery()).isNull(); assertThat(uri.getFragment()).isNull(); assertThat(uri.toString()).isEqualTo("scheme:"); assertThat(uri.isAbsolute()).isTrue(); @@ -165,7 +165,7 @@ public void parse_emptyPath() throws URISyntaxException { public void parse_emptyQuery() { Uri uri = Uri.create("scheme:?"); assertThat(uri.getScheme()).isEqualTo("scheme"); - assertThat(uri.getQuery()).isEmpty(); + assertThat(uri.getRawQuery()).isEmpty(); } @Test @@ -322,7 +322,6 @@ public void parse_decoding() throws URISyntaxException { assertThat(uri.getPort()).isEqualTo(1234); assertThat(uri.getPath()).isEqualTo("/p ath"); assertThat(uri.getRawPath()).isEqualTo("/p%20ath"); - assertThat(uri.getQuery()).isEqualTo("q uery"); assertThat(uri.getRawQuery()).isEqualTo("q%20uery"); assertThat(uri.getFragment()).isEqualTo("f ragment"); assertThat(uri.getRawFragment()).isEqualTo("f%20ragment"); @@ -336,9 +335,8 @@ public void parse_decodingNonAscii() throws URISyntaxException { @Test public void parse_decodingPercent() throws URISyntaxException { - Uri uri = Uri.parse("s://a/p%2520ath?q%25uery#f%25ragment"); + Uri uri = Uri.parse("s://a/p%2520ath#f%25ragment"); assertThat(uri.getPath()).isEqualTo("/p%20ath"); - assertThat(uri.getQuery()).isEqualTo("q%uery"); assertThat(uri.getFragment()).isEqualTo("f%ragment"); } @@ -420,7 +418,7 @@ public void toString_percentEncoding() throws URISyntaxException { .setScheme("s") .setHost("a b") .setPath("/p ath") - .setQuery("q uery") + .setRawQuery("q%20uery") .setFragment("f ragment") .build(); assertThat(uri.toString()).isEqualTo("s://a%20b/p%20ath?q%20uery#f%20ragment"); @@ -440,7 +438,6 @@ public void parse_transparentRoundTrip_ipLiteral() { assertThat(uri.getRawPath()).isEqualTo("/%4a%4B%2f%2F"); assertThat(uri.getPathSegments()).containsExactly("JK//"); assertThat(uri.getRawQuery()).isEqualTo("%4c%4D"); - assertThat(uri.getQuery()).isEqualTo("LM"); assertThat(uri.getRawFragment()).isEqualTo("%4e%4F"); assertThat(uri.getFragment()).isEqualTo("NO"); } @@ -459,7 +456,6 @@ public void parse_transparentRoundTrip_regName() { assertThat(uri.getRawPath()).isEqualTo("/%4a%4B%2f%2F"); assertThat(uri.getPathSegments()).containsExactly("JK//"); assertThat(uri.getRawQuery()).isEqualTo("%4c%4D"); - assertThat(uri.getQuery()).isEqualTo("LM"); assertThat(uri.getRawFragment()).isEqualTo("%4e%4F"); assertThat(uri.getFragment()).isEqualTo("NO"); } @@ -529,7 +525,7 @@ public void builder_encodingWithAllowedReservedChars() throws URISyntaxException .setUserInfo("u@") .setHost("a[]") .setPath("/p:/@") - .setQuery("q/?") + .setRawQuery("q/?") .setFragment("f/?") .build(); assertThat(uri.toString()).isEqualTo("s://u%40@a%5B%5D/p:/@?q/?#f/?"); @@ -600,7 +596,7 @@ public void builder_normalizesCaseWhereAppropriate() { .setScheme("hTtP") // #section-3.1 says producers (Builder) should normalize to lower. .setHost("aBc") // #section-3.2.2 says producers (Builder) should normalize to lower. .setPath("/CdE") // #section-6.2.2.1 says the rest are assumed to be case-sensitive - .setQuery("fGh") + .setRawQuery("fGh") .setFragment("IjK") .build(); assertThat(uri.toString()).isEqualTo("http://abc/CdE?fGh#IjK"); @@ -621,12 +617,32 @@ public void builder_canClearAllOptionalFields() { .setPath("") .setUserInfo(null) .setPort(-1) - .setQuery(null) + .setRawQuery(null) .setFragment(null) .build(); assertThat(uri.toString()).isEqualTo("http:"); } + @Test + public void builder_setRawQuery() { + Uri uri = Uri.newBuilder().setScheme("http").setHost("host").setRawQuery("%61=b&c=%64").build(); + assertThat(uri.getRawQuery()).isEqualTo("%61=b&c=%64"); + assertThat(uri.toString()).isEqualTo("http://host?%61=b&c=%64"); + } + + @Test + public void builder_setRawQuery_null() { + Uri uri = + Uri.newBuilder() + .setScheme("http") + .setHost("host") + .setRawQuery("a=b") + .setRawQuery(null) + .build(); + assertThat(uri.getRawQuery()).isNull(); + assertThat(uri.toString()).isEqualTo("http://host"); + } + @Test public void builder_canClearAuthorityComponents() { Uri uri = Uri.create("s://user@host:80/path").toBuilder().setRawAuthority(null).build(); @@ -692,7 +708,7 @@ public void toString_percentEncodingLiteralPercent() throws URISyntaxException { .setScheme("s") .setHost("a") .setPath("/p%20ath") - .setQuery("q%uery") + .setRawQuery("q%25uery") .setFragment("f%ragment") .build(); assertThat(uri.toString()).isEqualTo("s://a/p%2520ath?q%25uery#f%25ragment");