Best way to encode URL in Java

旧巷老猫 提交于 2019-12-12 10:16:14

问题


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



来源:https://stackoverflow.com/questions/5291586/best-way-to-encode-url-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!