Added URLDecoder cUnicode support

This commit is contained in:
Ziver Koc 2015-12-11 14:58:30 +01:00
parent bf235694eb
commit 930ad2b2f3
3 changed files with 40 additions and 20 deletions

BIN
Zutil.jar

Binary file not shown.

View file

@ -1,5 +1,9 @@
package zutil.parser; package zutil.parser;
import zutil.converters.Converter;
import java.io.UnsupportedEncodingException;
/** /**
* This utility class will decode Strings encoded with % sign's to a normal String * This utility class will decode Strings encoded with % sign's to a normal String
* *
@ -10,27 +14,40 @@ public class URLDecoder {
public static String decode(String url){ public static String decode(String url){
if(url == null) if(url == null)
return null; return null;
StringBuilder out = new StringBuilder();
for (int i=0; i<url.length(); ++i) { try {
char c = url.charAt(i); StringBuilder out = new StringBuilder();
switch (c){ byte[] buffer = null;
case '+': for (int i=0; i<url.length(); ++i) {
out.append(' '); char c = url.charAt(i);
break; switch (c){
case '%': case '+':
if (i+2 < url.length()) { out.append(' ');
char ascii = (char)Integer.parseInt("" + url.charAt(i + 1) + url.charAt(i + 2), 16); break;
out.append(ascii); case '%':
i += 2; if (i+2 < url.length()) {
} if(buffer == null)
else buffer = new byte[url.length()];
int bufferPos = 0;
while(i<url.length() && url.charAt(i) == '%') {
buffer[bufferPos++] = Converter.hexToByte(url.charAt(i + 1), url.charAt(i + 2));
i += 3;
}
--i; // Go back one step as i will be incremented in the main for loop
out.append(new String(buffer, 0, bufferPos, "UTF-8"));
}
else
out.append(c);
break;
default:
out.append(c); out.append(c);
break; break;
default: }
out.append(c);
break;
} }
return out.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); // Should never happen
} }
return out.toString(); return null;
} }
} }

View file

@ -3,6 +3,8 @@ package zutil.test;
import org.junit.Test; import org.junit.Test;
import zutil.parser.URLDecoder; import zutil.parser.URLDecoder;
import java.io.UnsupportedEncodingException;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@ -29,7 +31,8 @@ public class URLDecoderTest {
} }
@Test @Test
public void percentMultibyteTest(){ public void percentMultibyteTest() throws UnsupportedEncodingException {
assertEquals("Ängen", java.net.URLDecoder.decode("%C3%84ngen", "UTF-8"));
assertEquals("Ängen", URLDecoder.decode("%C3%84ngen")); assertEquals("Ängen", URLDecoder.decode("%C3%84ngen"));
} }
} }