package com.android.common.utils;


import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author 910040
 * @version 1.0
 * @date 2018/11/13
 * 编解码
 */
public class EncodeUtils {


    public static String urlEncode(final String input) {
        return urlEncode(input, "UTF-8");
    }


    public static String urlEncode(final String input, final String charsetName) {
        if (input == null || input.length() == 0) {
            return "";
        }
        try {
            return URLEncoder.encode(input, charsetName);
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError(e);
        }
    }


    public static String urlDecode(final String input) {
        return urlDecode(input, "UTF-8");
    }


    public static String urlDecode(final String input, final String charsetName) {
        if (input == null || input.length() == 0) {
            return "";
        }
        try {
            return URLDecoder.decode(input, charsetName);
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError(e);
        }
    }

    /**
     * base64编码
     * @param content 待编码内容
     * @return 编码后内容
     */
    public static byte[] base64Encode(String content) {
        try {
            byte[] contentByte = content.getBytes("utf-8");
            return Base64.encode(contentByte, Base64.DEFAULT);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * base64编码
     * @param content 待编码内容
     * @return 编码后内容
     */
    public static String base64Encode2String(String content) {
        byte[] contentByte = content.getBytes();
        return Base64.encodeToString(contentByte, Base64.DEFAULT);
    }

    /**
     * base64编码
     * @param content 待编码内容
     * @return 编码后内容
     */
    public static String base64Encode2String(byte[] content) {
        return Base64.encodeToString(content, Base64.DEFAULT);
    }

    /**
     * base64解码
     * @param content 待解码内容
     * @return 解码后内容
     */
    public static byte[] base64Decode(String content) {
        return Base64.decode(content, Base64.DEFAULT);
    }
}
