Skip to content

Commit f7b0749

Browse files
committed
Added Encoder class for URL encoding
1 parent 1b21db9 commit f7b0749

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package org.ocpsoft.urlbuilder.util;
2+
3+
import java.io.UnsupportedEncodingException;
4+
import java.net.URI;
5+
import java.net.URISyntaxException;
6+
import java.net.URLEncoder;
7+
import java.nio.charset.Charset;
8+
9+
public class Encoder
10+
{
11+
12+
private static final Charset UTF8 = Charset.forName("UTF-8");
13+
14+
/**
15+
* Encodes the given string as described in RFC 2396
16+
*/
17+
public static String path(String s)
18+
{
19+
try
20+
{
21+
final URI uri = new URI("http", "localhost", "/" + s, null);
22+
return uri.toASCIIString().substring(17);
23+
}
24+
catch (URISyntaxException e)
25+
{
26+
throw new IllegalArgumentException(e);
27+
}
28+
}
29+
30+
/**
31+
* Encodes the given string using HTML form encoding
32+
*/
33+
public static String query(String s)
34+
{
35+
try {
36+
return URLEncoder.encode(s, UTF8.name());
37+
}
38+
catch (UnsupportedEncodingException e) {
39+
throw new IllegalStateException(e);
40+
}
41+
}
42+
43+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package org.ocpsoft.urlbuilder.util;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import org.junit.Test;
6+
7+
public class EncoderTest
8+
{
9+
10+
@Test
11+
public void testPath()
12+
{
13+
assertEquals("test", Encoder.path("test"));
14+
assertEquals("hello%20world", Encoder.path("hello world"));
15+
assertEquals("a%7Cb", Encoder.path("a|b"));
16+
assertEquals("%5Btest%5D", Encoder.path("[test]"));
17+
assertEquals("%22a%22", Encoder.path("\"a\""));
18+
assertEquals("Really%3F", Encoder.path("Really?"));
19+
}
20+
21+
@Test
22+
public void testQuery()
23+
{
24+
assertEquals("test", Encoder.query("test"));
25+
assertEquals("hello+world", Encoder.query("hello world"));
26+
}
27+
28+
}

0 commit comments

Comments
 (0)