Mine is an Phonegap project supporting for two platforms(Android and IOS).

For any server request I need to set the authorization header.This Header should be in encoded base64 UTF-16LE format to receive the response.

I am able to encode it to base64 by using jquery base-64 plugin.

var base64Enc=$.base64.encode("Surya@gmail.com"+":"+"Password01");

This works fine.But I need to convert this into UTF-16LE which has to be set as authorization header for my request.

beforeSend: function(xhr){
             xhr.setRequestHeader("Content-Type", "application/json");
             xhr.setRequestHeader("Authorization", "Basic " + base64Enc);
        },

How can I convert base64Enc into UTF-16LE. In java i can do the same by using new String(Base64.encodeBase64("Surya@gmail.com:Password01".getBytes("UTF-16LE")))

Please help me how to do this in JavaScript/jquery.Does Jquery has any plugin to do this coversion or should I have to use any utilities to achive this.

Please help me on this.Thanks in advance.

有帮助吗?

解决方案

With the assumption that you don't have to support IE < 10, use native ECMAScript.

Use window.atob()1 and window.btoa()2

Since:

DOMStrings are 16-bit-encoded strings 3

/* Base64 Encode */ 
var base64Enc = window.btoa("Surya@gmail.com"+":"+"Password01");

/* Base64 Decode (as UTF16 DOMString) */
var utf16Dec = window.atob(base64Enc);

1 https://developer.mozilla.org/en-US/docs/Web/API/window.atob

2 https://developer.mozilla.org/en-US/docs/Web/API/window.btoa

3 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top