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
300 views
in Technique[技术] by (71.8m points)

java - Encode URL query parameters

How can I encode URL query parameter values? I need to replace spaces with %20, accents, non-ASCII characters etc.

I tried to use URLEncoder but it also encodes / character and if I give a string encoded with URLEncoder to the URL constructor I get a MalformedURLException (no protocol).

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

URLEncoder has a very misleading name. It is according to the Javadocs used encode form parameters using MIME type application/x-www-form-urlencoded.

With this said it can be used to encode e.g., query parameters. For instance if a parameter looks like &/?# its encoded equivalent can be used as:

String url = "http://host.com/?key=" + URLEncoder.encode("&/?#");

Unless you have those special needs the URL javadocs suggests using new URI(..).toURL which performs URI encoding according to RFC2396.

The recommended way to manage the encoding and decoding of URLs is to use URI

The following sample

new URI("http", "host.com", "/path/", "key=| ?/#?", "fragment").toURL();

produces the result http://host.com/path/?key=%7C%20?/%23?#fragment. Note how characters such as ?&/ are not encoded.

For further information, see the posts HTTP URL Address Encoding in Java or how to encode URL to avoid special characters in java.


EDIT

Since your input is a string URL, using one of the parameterized constructor of URI will not help you. Neither can you use new URI(strUrl) directly since it doesn't quote URL parameters.

So at this stage we must use a trick to get what you want:

public URL parseUrl(String s) throws Exception {
     URL u = new URL(s);
     return new URI(
            u.getProtocol(), 
            u.getAuthority(), 
            u.getPath(),
            u.getQuery(), 
            u.getRef()).
            toURL();
}

Before you can use this routine you have to sanitize your string to ensure it represents an absolute URL. I see two approaches to this:

  1. Guessing. Prepend http:// to the string unless it's already present.

  2. Construct the URI from a context using new URL(URL context, String spec)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

56.9k users

...