태터데스크 관리자

도움말
닫기
적용하기   첫페이지 만들기

태터데스크 메시지

저장하였습니다.
밤하늘의 실제별, 나도 가질 수 있다?!

[Flex,AIR,ActionScript3] URL 문자열 처리하는 클래스, encodeURL, decodeURL

2008/05/12 16:47

 

[공지]이미지나 링크가 깨졌다면 댓글 부탁드립니다.

이 글을 쓰고 나중에 안 사실이지만 아래 encodeURL, decodeURL은 Flex의 encodeURI, decodeURI와 동일한 함수이다. 이외에도 비슷한 함수는 encodeURIComponent, decodeURIComponent, escape, unescape가 있다. 참고하시길...


Flash를 Embed를 할 때,
swf확장자 뒤에 "플래시파일.swf?name=jidolstar&age=20" 형태로 넘겨줄 때가 있다.
이때 Flash나 Flex에서 name과 age의 변수값을 읽을 수 있다.
이 정보는 Flex의 경우 Application.application.parameters 를 통해 얻을 수 있고
URL자체는 Application.application.url 로 읽어올 수 있겠다.

때로는 "name=지돌스타" 대신 "name=%ec%a7%80%eb%8f%8c%ec%8a%a4%ed%83%80" 형태로 넘어올 경우가 있다.

이러한 URL관련 문자열을 한번에 다룰 수 있는 클래스를 만들어보았다.

package com.jidolstar.utils

{

       /**

        * URL 문자열을 처리하는 ActionScript3 클래스 <br>

        * mx.utils.URLUtil 중복을 피할 ~ ^^

        *

        * @author 지돌스타(http://blog.jidolstar.com, jidolstar@gmail.com)

        * @since 2008-05-12

        * @version 2008.05.02

        */

       public class URLUtil

       {

             /**

              * URL Encode 함수

              * <p>

              * ex)

              * <p>

              * trace(URLUtil.encodeURL("안녕하세요")); //%ec%95%88%eb%85%95%ed%95%98%ec%84%b8%ec%9a%94<br>

              * trace(URLUtil.encodeURL("This is the test for encode.")); //This+is+the+test+for+encode.

              *

              * @param str 엔코드할 문자열

              * @return 엔코드된 문자열

              *

              */          

             public static function encodeURL( str:String ):String

             {

                 var s0:String;

                 var i:int;

                 var s:String;

                 var u:int;

                

                 s0 = "";                // encoded str

                 for (i = 0; i < str.length; i++){   // scan the source

                     s = str.charAt(i);

                     u = str.charCodeAt(i);          // get unicode of the char

                     if (s == " "){s0 += "+";}       // SP should be converted to "+"

                     else {

                            if ( u == 0x2a || u == 0x2d || u == 0x2e || u == 0x5f || ((u >= 0x30) && (u <= 0x39)) || ((u >= 0x41) && (u <= 0x5a)) || ((u >= 0x61) && (u <= 0x7a))){       // check for escape

                             s0 = s0 + s;            // don't escape

                         }

                         else {                  // escape

                             if ((u >= 0x0) && (u <= 0x7f)){     // single byte format

                                 s = "0"+u.toString(16);

                                 s0 += "%"+ s.substr(s.length-2);

                             }

                             else if (u > 0x1fffff){     // quaternary byte format (extended)

                                 s0 += "%" + (0xf0 + ((u & 0x1c0000) >> 18)).toString(16);

                                 s0 += "%" + (0x80 + ((u & 0x3f000) >> 12)).toString(16);

                                 s0 += "%" + (0x80 + ((u & 0xfc0) >> 6)).toString(16);

                                 s0 += "%" + (0x80 + (u & 0x3f)).toString(16);

                             }

                             else if (u > 0x7ff){        // triple byte format

                                 s0 += "%" + (0xe0 + ((u & 0xf000) >> 12)).toString(16);

                                 s0 += "%" + (0x80 + ((u & 0xfc0) >> 6)).toString(16);

                                 s0 += "%" + (0x80 + (u & 0x3f)).toString(16);

                             }

                             else {                      // double byte format

                                 s0 += "%" + (0xc0 + ((u & 0x7c0) >> 6)).toString(16);

                                 s0 += "%" + (0x80 + (u & 0x3f)).toString(16);

                             }

                         }

                     }

                 }

            

                 return s0;             

             }

            

             /**

              * URL Decode 함수

              * <p>

              * ex)

              * <p>

              * trace(URLUtil.decodeURL("%ec%95%88%eb%85%95%ed%95%98%ec%84%b8%ec%9a%94")); //안녕하세요<br>

              * trace(URLUtil.decodeURL("This+is+the+test+for+encode.")); // This is the test for encode.

              *

              * @param str 디코드할 문자열

              * @return 디코드된 문자열

              *

              */                       

             public static function decodeURL( str:String ):String

             {

                 var s0:String;

                 var i:int;

                 var j:int;

                 var s:String;

                 var ss:String;

                 var sss:String;

                 var u:int;

                 var n:int;

                 var f:int;

                 s0 = "";                // decoded str

                

                 for (i = 0; i < str.length; i++) // scan the source str

                 { 

                     s = str.charAt(i);

                     if (s == "+"){s0 += " ";}       // "+" should be changed to SP

                     else {

                         if (s != "%"){s0 += s;}     // add an unescaped char

                         else{               // escape sequence decoding

                             u = 0;          // unicode of the character

                             f = 1;          // escape flag, zero means end of this sequence

                             while (true) {

                                 ss = "";        // local str to parse as int

                                     for (j = 0; j < 2; j++ ) {  // get two maximum hex characters for parse

                                         sss = str.charAt(++i);

                                         if (((sss >= "0") && (sss <= "9")) || ((sss >= "a") && (sss <= "f"))  || ((sss >= "A") && (sss <= "F"))) {

                                             ss += sss;      // if hex, add the hex character

                                         } else {--i; break;}    // not a hex char., exit the loop

                                     }

                                 n = parseInt(ss, 16);           // parse the hex str as byte

                                 if (n <= 0x7f){u = n; f = 1;}   // single byte format

                                 if ((n >= 0xc0) && (n <= 0xdf)){u = n & 0x1f; f = 2;}   // double byte format

                                 if ((n >= 0xe0) && (n <= 0xef)){u = n & 0x0f; f = 3;}   // triple byte format

                                 if ((n >= 0xf0) && (n <= 0xf7)){u = n & 0x07; f = 4;}   // quaternary byte format (extended)

                                 if ((n >= 0x80) && (n <= 0xbf)){u = (u << 6) + (n & 0x3f); --f;}         // not a first, shift and add 6 lower bits

                                 if (f <= 1){break;}         // end of the utf byte sequence

                                 if (str.charAt(i + 1) == "%"){ i++ ;}                   // test for the next shift byte

                                 else {break;}                   // abnormal, format error

                             }

                         s0 += String.fromCharCode(u);           // add the escaped character

                         }

                     }

                 }

                 return s0;             

             }

 

             /**

              * URL Query문자열을 해석하여 Object 반환한다.

              * <p>

              * ex)

              * var url:String = Application.application.url; //http://jidolstar.com/flex/URLUtilTest.swf?name=jidolstar&age=20<br>

              * var query:Object = URLUtil.parseURLQueryString(url);<br>

              * trace( query.name +", " + query.age ); //jidolstar, 20<br>

              *

              * @param url

              * @return Query문자열을 파싱하여 만들어진 Object

              *

              */

             public static function parseURLQueryString( url:String ):Object

             {

                    var obj:Object = null;

                     

                    try

                    {

                           // ? 포함한 ?앞의 모든 부분 삭제

                           // ex) http://a.com/content.swf?a=1&b=2 -> a=1&b=2

                           var myPattern:RegExp = /.*\?/;

                           var s:String = url;

                           s = s.replace( myPattern, "" );

                          

                           if( s.length == 0 ) return null;

                          

                           //& 구분으로 Array 만들기

                           var params:Array = s.split("&");

                           for each(var param:String in params)

                           {

                                 var value:Array = param.split("=");

                                 if( value.length == 2 )

                                 {

                                        if( obj == null ) obj = new Object;

                                        obj[value[0]] = value[1];

                                 }

                           }

                    }

                    catch( e:Error )

                    {

                           trace( "parseURLQueryString() msg=" + e );

                    }

                   

                    return obj;

             }     

            

                          

             /**

              * URL에서 Query 문자열을 제외한 순수 URL 얻어온다.

              *

              * <p>

              * ex)

              * <p>

              * trace( URLUtil.getURLExceptQueryString("http://jidolstar.com/content.swf?name=jidolstar&age=20") ); //http://jidolstar.com

              * 

              * @param url Query 문자열이 포함된 URL

              * @return Query 문자열을 제외한 URL

              *

              */

             public static function getURLExceptQueryString( url:String ):String

             {

                    var params:Array = url.split("?");

                    return params[0] as String; 

             }     

 

       }

}


만약 Flex라면 테스트는 이런식으로 해보자.

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">

       <mx:Script>

             <![CDATA[

                    import com.jidolstar.utils.URLUtil;

                   

                    private function init():void

                    {

                           var url:String = Application.application.url; //http://jidolstar.com/flex/URLUtilTest.swf?name=jidolstar&age=20

                           var obj:Object = URLUtil.parseURLQueryString(url);

                           trace(obj.name +","+obj.age);

                          

                           trace(URLUtil.encodeURL("지돌스타"));

                           trace(URLUtil.encodeURL("This is the test for encode."));

                           trace(URLUtil.decodeURL("%ec%95%88%eb%85%95%ed%95%98%ec%84%b8%ec%9a%94"));

                           trace(URLUtil.decodeURL("This+is+the+test+for+encode."));

                           trace( URLUtil.getURLExceptQueryString("http://jidolstar.com/content.swf?name=jidolstar&age=20"));

                    }

             ]]>

       </mx:Script>

</mx:Application>

위 코드에서 Application.application.url에 "http://jidolstar.com/flex/URLUtilTest.swf?name=jidolstar&age=20"로 표현되어 있는데 swf뒤에 ?뒷부분은 html-templete폴더안에 index.template.html에서 ${swf} 부분의 바로 뒤에 "?name=jidolstar&age=20"를 추가해 주면 되겠다.

결과는 아래와 같다.
jidolstar,20
%ec%a7%80%eb%8f%8c%ec%8a%a4%ed%83%80
This+is+the+test+for+encode.
안녕하세요
This is the test for encode.
http://jidolstar.com/content.swf

혹시 퍼가시면 댓글 남겨주시는 센스 발휘해 주삼~ ^^
만약 버그가 있다면 공유를~~~~

글쓴이 : 지돌스타(
http://blog.jidolstar.com/330)
크리에이티브 커먼즈 라이선스
Creative Commons License

Adobe Flash Platform , , , , ,

Trackback 주소: http://blog.jidolstar.com/trackback/330
  1. Blog Icon
    Good!!

    좋은정보 공유 감사합니다^^

  2. Blog Icon
    kyuni

    감사합니다...

  3. Blog Icon
    나그네

    감사합니다.

  4. Blog Icon
    오승훈

    좋은 정보 감사 합니다.
    딱 필요한 거였네요~ ^^

    그런데 php 의 urlencode, decode 방식과는 통용이 안되나요??

    php urlencode 한 값을 xml 로 받아서 처리 하려고 하고 있는데

    안되네요~ ?? ^^

  5. php로 해본적은 없어서 모르겠습니다. 스펙을 확인해보심이 어떨가요?

  6. php 와 연결해서 사용중입니다.
    잘 동작하는데요.... 이기회를 빌어서 지돌스타님께 감사의 말씀 전합니다.

  7. 감사합니다. ^^

  8. Blog Icon
    ㄱ나니

    정말 지돌스타님 초러브입니다. 항상 돌다돌다 지돌님 블로그에서 답을 얻네요
    감사합니다

  9. 안녕하세요. 도움이 되었다니 다행입니다.

  10. Blog Icon
    감사

    좋은 정보 감사합니다. 항상 도움을 받네요^^ 멋지세요~