'URLEncoder.encode`的正确编码

时间:2015-06-18 22:41:40

标签: java scala urlencode url-encoding

我正在尝试标准化网址中的邮件,而我正在使用URLEncoder.encode。我得到的问题是,输出似乎不是一个有效的网址。例如

val text = Some("test question (a) x (b) y").get
val query = "http://localhost:8080/ask?text=" + text
println(query)
val queryEnc = URLEncoder.encode(query, "UTF-8")
println(queryEnc)

输出:

http://localhost:8080/ask?text=test question (a) x (b) y
http%3A%2F%2Flocalhost%3A8080%2Fask%3Ftext%3Dtest+question+%28a%29+x+%28b%29+y

输出是否为有效网址? (它看起来没有效果,因为我机器上的Chrome和Safari无法识别它)。

1 个答案:

答案 0 :(得分:9)

您必须对每个参数值进行编码。不是整个网址。

<profile>
        <id>dev1</id>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <configuration>
                        <systemPropertyVariables>
                            <env>local</env>
                            <properties.file>src/test/resources/dev1.properties</properties.file>
                        </systemPropertyVariables>
                        <suiteXmlFiles>
                            <suiteXmlFile>src/test/resources/dev1.testng.xml</suiteXmlFile>
                        </suiteXmlFiles>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
    <profile>
        <id>dev2</id>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <configuration>
                        <systemPropertyVariables>
                            <env>local</env>
                            <properties.file>src/test/resources/dev2.properties</properties.file>
                        </systemPropertyVariables>
                        <suiteXmlFiles>
                            <suiteXmlFile>src/test/resources/dev2.testng.xml</suiteXmlFile>
                        </suiteXmlFiles>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>