有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (2) 个答案

  1. # 1 楼答案

    构建url,如下所示:

    String url = "http://www.hello.com/bar/foo?";
    url += "a=" + URLEncoder.encode(value_of_a);
    url += "&c=" + URLEncoder.encode(value_of_c);
    
  2. # 2 楼答案

    我将离开实际的component encoding as a user-supplied function,因为它是一个已经存在且讨论得很好的问题,没有一个简单的JCL解决方案。。在任何情况下,下面是我在不使用第三方库的情况下如何处理这个特定问题的方法

    虽然正则表达式有时会导致two problems,但我不太愿意建议一种更严格的方法,比如URI,因为我不知道它将如何——或者甚至是否会——处理这些令人讨厌的无效URL。因此,这里是一个使用带有dynamic replacement value的正则表达式的解决方案

    // The following pattern is pretty liberal on what it matches;
    // It ought to work as long as there is no unencoded ?, =, or & in the URL
    // but, being liberal, it will also match absolute garbage input.
    Pattern p = Pattern.compile("\\b(\\w[^=?]*)=([^&]*)");
    Matcher m = p.matcher("http://www.hello.com/bar/foo?a=,b &c =d");
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String key = m.group(1);
        String value = m.group(2);
        m.appendReplacement(sb,
            encodeURIComponent(key) + "=" encodeURIComponent(value));
    }
    m.appendTail(sb);
    

    请参见ideone example示例,其中填充了encodeURIComponent