Java - 将字符串转换为有效的URI对象 [英] Java - Convert String to valid URI object
问题描述
我正在尝试从 String
中获取一个 java.net.URI
对象。该字符串具有一些字符,它们需要由其百分比转义序列替换。但是当我使用URLEncoder对UTF-8编码的字符串进行编码时,即使使用/代替它们的转义序列。
I am trying to get a java.net.URI
object from a String
. The string has some characters which will need to be replaced by their percentage escape sequences. But when I use URLEncoder to encode the String with UTF-8 encoding, even the / are replaced with their escape sequences.
如何获取有效的编码URL String对象?
How can I get a valid encoded URL from a String object?
http:// www.google.com?q=a b 给出了 http%3A%2F%2www.google.com ... ,而我希望输出为 http://www.google.com?q=a%20b
http://www.google.com?q=a b gives http%3A%2F%2www.google.com... whereas I want the output to be http://www.google.com?q=a%20b
有人可以告诉我如何实现这一点。
Can someone please tell me how to achieve this.
我在Android应用中尝试这样做。所以我可以访问有限数量的库。
I am trying to do this in an Android app. So I have access to a limited number of libraries.
推荐答案
您可以尝试: org.apache。 commons.httpclient.util.URIUtil.encodeQuery
在 Apache commons-httpclient 项目
像这样(见 URIUtil ):
URIUtil.encodeQuery("http://www.google.com?q=a b")
将成为:
http://www.google.com?q=a%20b
你当然可以自己做,但是URI解析可能会变得很混乱...
You can of course do it yourself, but URI parsing can get pretty messy...
这篇关于Java - 将字符串转换为有效的URI对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!