Parsing query strings on Android

前端 未结 25 1277
时光说笑
时光说笑 2020-11-22 17:41

Java EE has ServletRequest.getParameterValues().

On non-EE platforms, URL.getQuery() simply returns a string.

What\'s the normal way to properly parse the qu

25条回答
  •  孤城傲影
    2020-11-22 17:53

    I have methods to achieve this:

    1):

    public static String getQueryString(String url, String tag) {
        String[] params = url.split("&");
        Map map = new HashMap();
        for (String param : params) {
            String name = param.split("=")[0];
            String value = param.split("=")[1];
            map.put(name, value);
        }
    
        Set keys = map.keySet();
        for (String key : keys) {
            if(key.equals(tag)){
             return map.get(key);
            }
            System.out.println("Name=" + key);
            System.out.println("Value=" + map.get(key));
        }
        return "";
    }
    

    2) and the easiest way to do this Using Uri class:

    public static String getQueryString(String url, String tag) {
        try {
            Uri uri=Uri.parse(url);
            return uri.getQueryParameter(tag);
        }catch(Exception e){
            Log.e(TAG,"getQueryString() " + e.getMessage());
        }
        return "";
    }
    

    and this is an example of how to use either of two methods:

    String url = "http://www.jorgesys.com/advertisements/publicidadmobile.htm?position=x46&site=reform&awidth=800&aheight=120";      
    String tagValue = getQueryString(url,"awidth");
    

    the value of tagValue is 800

提交回复
热议问题