Java String Encode encode(String src)

Here you can find the source of encode(String src)

Description

encode

License

Open Source License

Declaration

public static String encode(String src) 

Method Source Code


//package com.java2s;
/*//from  w  ww  .jav a  2s . c  om
 * URIUtils.java
 *
 * Copyright 2008 Mark Logic Corporation.
 * All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.UnsupportedEncodingException;

public class Main {
    public static String encode(String src) {
        String genDelims = ":/?#[]@";
        String subDelims = "!$&'()*+,;=";
        String unreserved = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~";
        String okChars = genDelims + subDelims + unreserved + "%"; // don't double-escape %-escaped chars!

        // FIXME: This should be more general, but Windows seems to be the only problem
        // and I'm to lazy to look up how to dyanmically escape "\"
        String filesep = System.getProperty("file.separator");
        if ("\\".equals(filesep)) {
            src = src.replaceAll("\\\\", "/");
        }

        String encoded = "";

        try {
            byte[] bytes = src.getBytes("UTF-8");
            for (int pos = 0; pos < bytes.length; pos++) {
                if (okChars.indexOf(bytes[pos]) >= 0) {
                    encoded += (char) bytes[pos];
                } else {
                    encoded += String.format("%%%02X", bytes[pos]);
                }
            }
        } catch (UnsupportedEncodingException uee) {
            // This can't happen for UTF-8!
        }

        return encoded;
    }
}

Related

  1. encode(String s)
  2. encode(String s)
  3. encode(String s, String enc)
  4. encode(String s, String encoding)
  5. encode(String source, String charsetFrom, String charsetTo)
  6. encode(String src, String charset)
  7. encode(String str)
  8. encode(String str, int start, int end, Writer writer)
  9. encode(String text, String charset)