Java URL Encode encodeURL(String s)

Here you can find the source of encodeURL(String s)

Description

Encodes a String into UTF-8 for use in an URL query string or html POST data.

License

Apache License

Declaration

public static String encodeURL(String s) 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.io.UnsupportedEncodingException;

public class Main {
    private static final String HEX_DIGITS = "0123456789ABCDEF";

    /**// w  ww  .j  ava  2 s  . co m
     * Encodes a String into UTF-8 for use in an URL query string or html POST
     * data.
     */
    public static String encodeURL(String s) {
        try {
            byte[] utf8 = s.getBytes("UTF-8");

            int len = utf8.length;
            StringBuffer sbuf = new StringBuffer(len);

            for (int i = 0; i < len; i++) {
                int ch = utf8[i];

                if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z') || ('0' <= ch && ch <= '9')
                        || (ch == '-' || ch == '_' || ch == '.' || ch == '!' || ch == '~' || ch == '*' || ch == '\''
                                || ch == '(' || ch == ')')) {
                    sbuf.append((char) ch);
                } else if (ch == ' ') {
                    sbuf.append('+');
                } else {
                    sbuf.append('%');
                    sbuf.append(HEX_DIGITS.charAt((ch >> 4) & 0xF));
                    sbuf.append(HEX_DIGITS.charAt(ch & 0xF));
                }
            }
            return sbuf.toString();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException();
        }
    }
}

Related

  1. encodeStringURL(String str)
  2. encodeUri(String url)
  3. encodeURIComponent(String input)
  4. encodeURL(BitSet urlsafe, byte[] bytes)
  5. encodeUrl(final String input)
  6. encodeURL(String s)
  7. encodeUrl(String url, String encoding)
  8. encodeURLComponent(final String s)
  9. encodeUrlPath(String pathSegment)