I need to generate an url with an array parameter, or looking like so:
?array_name[]=value1&array_name[]=value2
How to achieve this with Uri.Builder
? The following code:
Uri.Builder builder = new Uri.Builder();
builder.appendQueryParameter("array[]", "one");
builder.appendQueryParameter("array[]", "another");
String result = builder.build().toString();
Gets me this output:
?array%5B%5D=one&array%5B%5D=another
In which square brackets are escaped.
How do I obtain the result that I want? I wouldn't like to ditch Uri.Builder
altogether as the solution is already based on that class.
Not "all URLs are URIs". It depends on the interpretation of the RFC. For example in Java the URI parser does not like [ or ] and that's because the spec says "should not" and not "shall not"
This means that square brackets can't be straightly added in a URI (without encoding).
"[IPv6 host addresses] is the only place where square bracket characters are allowed in the URI syntax." If you use them in the right place, java.net.URI accepts them. new java.net.URI("foo://[1080:0:0:0:8:800:200C:417A]/a/b") succeeds for me in Java 1.7. "foo://example.com/a[b]" errors. This sounds in line with the RFC. The form new URI("http", "example.com", "/a/b[c]!$&'()*+", null, null) will %-encode the []. That java.net.URL accepts them elsewhere sounds like it's doing less validation
Do you really need to use array_name[]
as name for your parameter? What exactly do you wish to achieve with ?array_name[]=value1&array_name[]=value2
?
I think your best choice (and time saver choice) is to change your parameters name.
Your URI is constructed correctly. You encode []
to %5B%5D
and then whoever receives your request should decode it. Still the answer to your specific question, if you can put []
into your URI is no.