2013-08-13

2013-08-13 12:53
JavaでjavascriptのencodeURIComponentメッソドを使う必要がありまして、
整理しておきます。


1. escape()がencode出来ない文字 : @*/+
2. encodeURI()がencode出来ない文字 : ~!@#$&*()=:/,;?+'
3. encodeURIComponent()がencode出来ない文字 : ~!*()'
※URIエンコードをするためには大体encodeURIComponent()を利用する

下記のURLを参照しました。
Thanks a lot John Topley!
http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-output
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
  
/**
 * Utility class for JavaScript compatible UTF-8 encoding and decoding.
 * 
 * @see http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-output
 * @author John Topley 
 */
public class EncodingUtil {
   
 /**
  * Decodes the passed UTF-8 String using an algorithm that's compatible with
  * JavaScript's decodeURIComponent function. Returns
  * null if the String is null.
  *
  * @param s The UTF-8 encoded String to be decoded
  * @return the decoded String
  */
 public static String decodeURIComponent(String s) {
  if (s == null) {
   return null;
  }
    
  String result = null;
  try {
   result = URLDecoder.decode(s, "UTF-8");
  } // This exception should never occur.
  catch (UnsupportedEncodingException e) {
   result = s;
  }
  return result;
 }
  
 /**
  * Encodes the passed String as UTF-8 using an algorithm that's compatible
  * with JavaScript's encodeURIComponent function. Returns
  * null if the String is null.
  * 
  * @param s The String to be encoded
  * @return the encoded String
  */
 public static String encodeURIComponent(String s) {
 String result = null;
   
 try {
 result = URLEncoder.encode(s, "UTF-8")
         .replaceAll("\\+", "%20")
         .replaceAll("\\%21", "!")
         .replaceAll("\\%27", "'")
         .replaceAll("\\%28", "(")
         .replaceAll("\\%29", ")")
         .replaceAll("\\%7E", "~");
 }// This exception should never occur.
 catch (UnsupportedEncodingException e)  {
  result = s;
 }
   
 return result;
 }
   
 /**
  * Private constructor to prevent this class from being instantiated.
  */
 private EncodingUtil() {
  super();
 }
}

次の投稿
Previous
This is the last post.

0 コメント:

コメントを投稿