根据指定的参数截取URL然后获取指定参数的参数值

public static void main(String[] args) {
    String url = "https://web?id=1&page=12&name=吴彭正¶m=111";
    String result  = urlSplit(url,"name");
    System.out.println(result);
}

/**
 * 解析出url参数中的键值对
 * 如 "index.jsp?Action=del&id=123",解析出Action:del,id:123存入map中
 * 根据参数名称获取参数后面的值
 * @param URL url地址
 * @return url请求参数部分
 * @author lzf
 */
public static String urlSplit(String URL, String params) {
    String result = null ;
    Map mapRequest = new HashMap();
    String[] arrSplit = null;
    String strUrlParam = TruncateUrlPage(URL);
    if (strUrlParam == null) {
        return null;
    }
    arrSplit = strUrlParam.split("[&]");
    for (String strSplit : arrSplit) {
        String[] arrSplitEqual = null;
        arrSplitEqual = strSplit.split("[=]");
        //解析出键值
        if (arrSplitEqual.length > 1) {
            //正确解析
            mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
        } else {
            if (arrSplitEqual[0] != "") {
                //只有参数没有值,不加入
                mapRequest.put(arrSplitEqual[0], "");
            }
        }
    }
    Iterator> it = mapRequest.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry entry = it.next();
        if(entry.getKey().equals(params)){
            result =  entry.getValue();
        }
    }
    return result;
}


private static String TruncateUrlPage(String strURL) {
    String strAllParam = null;
    String[] arrSplit = null;
    arrSplit = strURL.split("[?]");
    if (strURL.length() > 1) {
        if (arrSplit.length > 1) {
            for (int i = 1; i < arrSplit.length; i++) {
                strAllParam = arrSplit[i];
            }
        }
    }
    return strAllParam;
}

你可能感兴趣的:(Java基础)