Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Parse a URL in J2ME

I'm trying to extract the query's name-value pairs from a URL using J2ME, but it doesn't make it easy. J2ME doesn't have the java.net.URL class nor does String have a split method.

Is there a way to extract name-value pairs from a URL using J2ME? Any open source implementations would be welcome too.

like image 720
Cristian Avatar asked Dec 30 '22 06:12

Cristian


2 Answers

I like kchau answer but i just changed the data structure from two arrays to one Hashtable. This will also help if the number of URL parameters is unknown.

    String url = "http://www.so.com?name1=value1&name2=value2&name3=value3";

    Hashtable values = new Hashtable();

    int s = url.indexOf("?");  
    int e = 0;

    while (s != -1) {
        e = url.indexOf("=", s);              
        String name = url.substring(s + 1, e);
        s = e + 1;                            
        e = url.indexOf("&", s);              

        if (e < 0) {
            values.put(name, url.substring(s, url.length()));
        } else {        
            values.put(name, url.substring(s, e));
        }

        s = e;
    }

    for (Enumeration num = values.keys(); num.hasMoreElements();) {
            String key = (String)num.nextElement();
            System.out.println(key + "  " + values.get(key));
    }
like image 124
Mark Avatar answered Jan 05 '23 01:01

Mark


Here's my stab at it, some similarity to David's answer.

    String url = "http://www.stackoverflow.com?name1=value1&name2=value2&name3=value3";

    String[] names  = new String[10];
    String[] values = new String[10];

    int s = url.indexOf("?");  // Get start index of first name
    int e = 0, idx = 0;

    while (s != -1) {
        e = url.indexOf("=", s);              // Get end index of name string
        names[idx] = url.substring(s+1, e);
        s = e + 1;                            // Get start index of value string
        e = url.indexOf("&", s);              // Get index of next pair

        if (e < 0)  // Last pair
            values[idx] = url.substring(s, url.length());
        else        // o.w. keep storing
            values[idx] = url.substring(s, e);

        s = e;
        idx++;
    }

    for(int x = 0; x < 10; x++)
        System.out.println(names[x] +" = "+ values[x]);

Tested it, and I think it works. Hope it helps, good luck.

like image 35
kafuchau Avatar answered Jan 05 '23 00:01

kafuchau