爪哇 - 字符串转换为有效的URI对象爪哇、转换为、字符串、对象

2023-09-11 20:31:40 作者:丨谁的浮生乱了我的红尘丶

我想从一个字符串 A java.net.URI中对象。串具有一定的字符,这将需要通过百分比转义序列来替换。但是当我使用URLEn codeR为en code使用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.

我怎样才能得到一个有效的连接codeD URL从一个String对象?

How can I get a valid encoded URL from a String object?

http://www.google.com?q=ab 提供的的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.en codeQuery 在阿帕奇公地httpclient的项目

这样的(见URIUtil):

URIUtil.encodeQuery("http://www.google.com?q=a b")

将变成:

http://www.google.com?q=a%20b

当然你也可以自己做,但URI解析可以得到pretty的凌乱......

You can of course do it yourself, but URI parsing can get pretty messy...