decode URL with your own algorithm - Java Network

Java examples for Network:URL

Description

decode URL with your own algorithm

Demo Code


//package com.java2s;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.StringTokenizer;

public class Main {
    public static String decodeURL(String s) {
        if (s == null) {
            return "";
        }//from w  w  w  .  j  a v a 2s. c o m
        if (s.indexOf('+') < 0) {
            try {
                return URLDecoder.decode(s, "UTF-8");
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                return "";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return "";
            }
        }
        StringTokenizer st = new StringTokenizer(s, "+", true);
        StringBuilder sb = new StringBuilder();
        while (st.hasMoreTokens()) {
            String tk = st.nextToken();
            if ("+".equals(tk)) {
                sb.append("+");
            } else {
                try {
                    tk = URLDecoder.decode(tk, "UTF-8");
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                sb.append(tk);
            }
        }
        return sb.toString();
    }
}

Related Tutorials