|
1 | 1 | package com.baeldung.encoderdecoder; |
2 | 2 |
|
3 | | -import org.hamcrest.CoreMatchers; |
4 | | -import org.junit.Assert; |
5 | | -import org.junit.Test; |
6 | | -import org.slf4j.Logger; |
7 | | -import org.slf4j.LoggerFactory; |
| 3 | +import static java.util.stream.Collectors.joining; |
| 4 | +import static org.hamcrest.CoreMatchers.is; |
8 | 5 |
|
9 | 6 | import java.io.UnsupportedEncodingException; |
10 | | -import java.net.*; |
| 7 | +import java.net.URL; |
| 8 | +import java.net.URLDecoder; |
| 9 | +import java.net.URLEncoder; |
11 | 10 | import java.nio.charset.StandardCharsets; |
12 | 11 | import java.util.Arrays; |
13 | 12 | import java.util.HashMap; |
14 | 13 | import java.util.Map; |
15 | 14 |
|
16 | | -import static java.util.stream.Collectors.joining; |
17 | | -import static org.hamcrest.CoreMatchers.*; |
| 15 | +import org.hamcrest.CoreMatchers; |
| 16 | +import org.junit.Assert; |
| 17 | +import org.junit.Test; |
| 18 | +import org.slf4j.Logger; |
| 19 | +import org.slf4j.LoggerFactory; |
| 20 | +import org.springframework.web.util.UriUtils; |
18 | 21 |
|
19 | 22 | public class EncoderDecoderUnitTest { |
20 | 23 |
|
@@ -76,19 +79,20 @@ public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Ex |
76 | 79 |
|
77 | 80 | private String encodePath(String path) { |
78 | 81 | try { |
79 | | - path = new URI(null, null, path, null).getPath(); |
80 | | - } catch (URISyntaxException e) { |
| 82 | + path = UriUtils.encodePath(path, "UTF-8"); |
| 83 | + } catch (UnsupportedEncodingException e) { |
81 | 84 | LOGGER.error("Error encoding parameter {}", e.getMessage(), e); |
82 | 85 | } |
83 | 86 | return path; |
84 | 87 | } |
85 | 88 |
|
86 | 89 | @Test |
87 | | - public void givenPath_thenEncodeDecodePath() throws URISyntaxException { |
88 | | - URI uri = new URI(null, null, "/Path 1/Path+2", null); |
89 | | - |
90 | | - Assert.assertEquals("/Path 1/Path+2", uri.getPath()); |
91 | | - Assert.assertEquals("/Path%201/Path+2", uri.getRawPath()); |
| 90 | + public void givenPathSegment_thenEncodeDecode() throws UnsupportedEncodingException { |
| 91 | + String pathSegment = "/Path 1/Path+2"; |
| 92 | + String encodedPathSegment = encodePath(pathSegment); |
| 93 | + String decodedPathSegment = UriUtils.decode(encodedPathSegment, "UTF-8"); |
| 94 | + Assert.assertEquals("/Path%201/Path+2", encodedPathSegment); |
| 95 | + Assert.assertEquals("/Path 1/Path+2", decodedPathSegment); |
92 | 96 | } |
93 | 97 |
|
94 | 98 | @Test |
|
0 commit comments