Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

http - Is a trailing ampersand legal in a URL?

A URL like

http://localhost/path?a=b&c=d

is fine - but what is the status of the same URL with a trailing ampersand?

http://localhost/path?a=b&c=d&

For example the Java Servlet API allows it where Scala's Spray does not (ie it throws an error).

I've tried to find the answer in the URI syntax spec, but not sure how to parse their grammar.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The URI syntax spec is for generic URIs. It allows anything in the query. I am not aware of any specification which actually specifies ampersand-separated key=value pairs. I believe it is merely convention. I know that PHP, for example, offers an option for using a different separator. But now, everyone uses ampersand-separated things when they want key-value pairs. You still occasionally come across things which use it for just a simple string, e.g. http://example.com/?example. This is perfectly valid.

The basic answer, though, is that & is valid anywhere in the query string, including at the end.


Demistifying the RFC syntax, or Why & is valid anywhere in the query string:

First, you have

query       = *( pchar / "/" / "?" )

(So a query string is made of any number of pchar and literal slashes and question marks.)

Going back, you have

pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"

And earlier still

sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
            / "*" / "+" / "," / ";" / "="

So a literal & is in sub-delims which is in pchar, so it's valid in query


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...