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.
如何从 String 对象中获取有效的编码 URL?
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
in Apache commons-httpclient 项目
You might try: org.apache.commons.httpclient.util.URIUtil.encodeQuery
in Apache commons-httpclient project
像这样(见 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屋!