Converting string to web-safe Base64 format

橙三吉。 提交于 2019-11-27 14:54:33

The API requires you to use URL-safe base64 encoding. After doing the base64 encoding, try replacing / with _ and + with -. Details at:

https://developers.google.com/admin-sdk/directory/v1/reference/users/photos/update

I know that this is quite old, but I'm working in something similar and I want to share my solution. You can use this function to convert your string to a base64safeurl string:

protected static string Base64ForUrlEncode(string str)
        {

            StringBuilder result = new StringBuilder(Convert.ToBase64String(Encoding.ASCII.GetBytes(str)).TrimEnd('='));
            result.Replace('+', '-');
            result.Replace('/', '_');
            return result.ToString();
        }

More info here: http://www.codeproject.com/Tips/76650/Base-base-url-base-url-and-z-base-encoding

Note: This is C# code, so this solution is for .NET developments.

To add to @Jay lee's and @Daniel Marin's answers:

if you are using Python to encode, you can use:

base64.urlsafe

function, and in Java, you can use:

Base64.encodeBase64URLSafeString(byte[] binaryData)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!