1 11 package org.eclipse.help.internal.util; 12 13 import java.io.ByteArrayOutputStream ; 14 import java.io.UnsupportedEncodingException ; 15 16 public class URLCoder { 17 18 public static String encode(String s) { 19 try { 20 return urlEncode(s.getBytes("UTF8")); } catch (UnsupportedEncodingException uee) { 22 return null; 23 } 24 } 25 26 public static String decode(String s) { 27 try { 28 return new String (urlDecode(s), "UTF8"); } catch (UnsupportedEncodingException uee) { 30 return null; 31 } 32 } 33 34 private static String urlEncode(byte[] data) { 35 StringBuffer buf = new StringBuffer (data.length); 36 for (int i = 0; i < data.length; i++) { 37 buf.append('%'); 38 buf.append(Character.forDigit((data[i] & 240) >>> 4, 16)); 39 buf.append(Character.forDigit(data[i] & 15, 16)); 40 } 41 return buf.toString(); 42 } 43 44 private static byte[] urlDecode(String encodedURL) { 45 int len = encodedURL.length(); 46 ByteArrayOutputStream os = new ByteArrayOutputStream (len); 47 for (int i = 0; i < len;) { 48 switch (encodedURL.charAt(i)) { 49 case '%': 50 if (len >= i + 3) { 51 os.write(Integer.parseInt(encodedURL.substring(i + 1, i + 3), 16)); 52 } 53 i += 3; 54 break; 55 case '+': os.write(' '); 57 i++; 58 break; 59 default: 60 os.write(encodedURL.charAt(i++)); 61 break; 62 } 63 64 } 65 return os.toByteArray(); 66 } 67 } 68 | Popular Tags |