From 3a27d6b50e844626ad525d4a5363e5cb73ca3649 Mon Sep 17 00:00:00 2001 From: Sunil Gulabani Date: Wed, 12 Oct 2016 10:33:48 +0530 Subject: [PATCH] BAEL-255: Added encode-decode of url --- .../encoderdecoder/EncoderDecoder.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java diff --git a/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java b/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java new file mode 100644 index 0000000000..62d2663994 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/encoderdecoder/EncoderDecoder.java @@ -0,0 +1,38 @@ +package com.baeldung.encoderdecoder; + +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Test; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +public class EncoderDecoder { + + @Test + public void givenPlainURL_whenUsingUTF8EncodingScheme_thenEncodeURL() throws UnsupportedEncodingException { + String plainURL = "http://www.baeldung.com" ; + String encodedURL = URLEncoder.encode(plainURL, StandardCharsets.UTF_8.toString()); + + Assert.assertThat("http%3A%2F%2Fwww.baeldung.com", CoreMatchers.is(encodedURL)); + } + + @Test + public void givenEncodedURL_whenUsingUTF8EncodingScheme_thenDecodeURL() throws UnsupportedEncodingException { + String encodedURL = "http%3A%2F%2Fwww.baeldung.com" ; + String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_8.toString()); + + Assert.assertThat("http://www.baeldung.com", CoreMatchers.is(decodedURL)); + } + + @Test + public void givenEncodedURL_whenUsingWrongEncodingScheme_thenDecodeInvalidURL() throws UnsupportedEncodingException { + String encodedURL = "http%3A%2F%2Fwww.baeldung.com"; + + String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_16.toString()); + + Assert.assertFalse("http://www.baeldung.com".equals(decodedURL)); + } +}