Abhiram Diddigi home

A Server side function to Percent Encode

If you aren’t sure what is Percent Encode, Here is the RFC describing it.

If you aren’t sure why you need Percent Encode, Here is the link to Twitter oAuth Percent Encode page. We basically encode out parameters, when we send out Authorizations/Requests using oAuth protocol. I was working with a couple of such services, which only accept oAuth and desperately needed a Server Side solution. If you need it on the Client Side, there is a more elegant solution  - You can use encodeURI or encodeURIComponent. Linking an excellent post covering both these functions.

This post specifically speaks about the Server Side function of Percent Encode, for Service Now.

Note: This post uses Package calls. After Calagry, Package calls are no longer supported. Use the Calgary Package Migration tool to migrate your package calls.

Without further ado, Here is the script:

[code lang=”javascript”]

percentEncode:function(params){

  if(typeof params =='string'){

     var ENCODING = "UTF-8";
     var s = params;
     s= s.toString();
     var a = Packages.java.net.URLEncoder.encode(s, ENCODING)
     .replace("+", "%20").replace("*", "%2A")
     .replace("%7E", "~");

     return a;

  }

  if(typeof params == 'object'){
     var arr = [];

     for(var i in params){
        if (params.hasOwnProperty(i)) {
           gs.log("percent encodes"+ this.percentEncode(i)+"="+this.percentEncode(params[i]));
		   arr.push(this.percentEncode(i)+"="+this.percentEncode(params[i]));

        }

     }

      return arr.join('&');

  }

},

[/code]

Twitter is just an example of a service which uses Percent Encode. Percent Encode will(mostly) be used when ever you work with oAuth protocol, which Service Now is yet to introduce. On a side note, We can still mimic oAuth using HTTPClient’s  GET and POST.

Let me know what you think in the comments.