get Param Value from url query string - Android java.net

Android examples for java.net:URL

Description

get Param Value from url query string

Demo Code

import java.net.MalformedURLException;
import java.net.URL;
import java.util.StringTokenizer;

public class Main {
  public static boolean equals(String str1, String str2) {
    return str1 == null ? str2 == null : str1.equals(str2);
  }/*from   w w w .  j a  v a 2 s. co m*/

  public static String getParamValue(String url, String param) {
    if ((url == null) || (param == null))
      return null;

    StringBuffer sb = new StringBuffer();
    try {
      String[] arrStr = split(new URL(url).getQuery(), "&");
      for (String str : arrStr) {
        String[] compare = split(str, "=");
        if (equals(param, compare[0])) {
          sb.append(compare[1]);
          break;
        }
      }
    } catch (MalformedURLException e) {
    }

    return sb.toString();
  }

  public static String[] split(String str, String separator) {
    if (str == null) {
      return null;
    }
    String[] result;
    int i = 0; // index into the next empty array element

    StringTokenizer st = new StringTokenizer(str, separator);
    result = new String[st.countTokens()];
    while (st.hasMoreTokens()) {
      result[i++] = st.nextToken();
    }

    return result;
  }

}

Related Tutorials