Java - 将字符串转换为有效的URI对象

74
我正在尝试从一个字符串中获取java.net.URI对象。该字符串包含一些字符,需要替换为它们的百分比转义序列。但是当我使用URLEncoder以UTF-8编码对字符串进行编码时,甚至/也会被替换为它们的转义序列。
我如何从String对象中获得有效的编码URL? http://www.google.com?q=a b给出的结果是http%3A%2F%2www.google.com...,而我想要的输出结果是http://www.google.com?q=a%20b 请问有人能告诉我如何实现这一点。
我正在尝试在Android应用程序中完成此操作。因此,我只有访问有限数量的库。
11个回答

0

我最终使用了httpclient-4.3.6:

import org.apache.http.client.utils.URIBuilder;
public static void main (String [] args) {
    URIBuilder uri = new URIBuilder();
    uri.setScheme("http")
    .setHost("www.example.com")
    .setPath("/somepage.php")
    .setParameter("username", "Hello Günter")
    .setParameter("p1", "parameter 1");
    System.out.println(uri.toString());
}

输出将会是:

http://www.example.com/somepage.php?username=Hello+G%C3%BCnter&p1=paramter+1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接