Best way to encode URL in Java

2019-05-31 13:22发布

问题:

HI guys,

I have a URL and I want to embed it in the body of a mailto. Till now, I've tried 2 methods to encode the URL and both of them did not give me good results:

URLEncoder - this gave me plus signs in the e-mail message since apparently URLEncoder is appropriate for query parameters only.

org.apache.commons.httpclient.URI - this doesn't give me the complete URL. It gives me the same results as I had explained in a post earlier here: Escape & symbol in MailTo

What can I do?

Thanks :) Krt_Malta

回答1:

How about using URIUtil from httpclient?

URIUtil.encodeQuery(strUrl, "UTF-8");

Encoding the following address mailto:jo han.sjoberg@m.com gives mailto:jo%20han.sj%C3%83%C2%B6berg@m.com

Technically though, both + and %20 are acceptable encoding for a whitespace.



回答2:

Since spaces are converted to +, would it be sufficient to just replace all instances of + with %20 in the body?

mailto: ?subject=Look at this link&body=Check%20out%20this%20too%20http://localhost:9001/view/shopindex/display?keyword=test%26searchPostcode=Postcode"

Demo