Copied from URLDecoder.java - Java Network

Java examples for Network:Http

Description

Copied from URLDecoder.java

Demo Code


//package com.java2s;

import java.io.UnsupportedEncodingException;

public class Main {
    public static void main(String[] argv) throws Exception {
        String s = "java2s.com";
        System.out.println(decode(s));
    }//w  w  w.  j  a v  a  2s  .  c o  m

    /**
     * Copied from URLDecoder.java
     */
    public static String decode(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
            case '+':
                sb.append(' ');
                break;
            case '%':
                try {
                    sb.append((char) Integer.parseInt(
                            s.substring(i + 1, i + 3), 16));
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException(s);
                }
                i += 2;
                break;
            default:
                sb.append(c);
                break;
            }
        }
        // Undo conversion to external encoding
        String result = sb.toString();
        try {
            byte[] inputBytes = result.getBytes("8859_1");
            result = new String(inputBytes);
        } catch (UnsupportedEncodingException e) {
            // The system should always have 8859_1
        }
        return result;
    }
}

Related Tutorials