我想要一种方法来从 Java 中的 URL 参数中提取有时可能包含“& 和 =”的值

I want a method to extract Values that may sometimes contain "& and =" from URL parameters in Java

package com.bml.icbs.ws.param;    
import java.util.HashMap;

public class 请求参数{

private String param;
private HashMap<String, String> hashmap;

    public RequestParameter(String param){

    this.param=param;
    this.hashmap = new HashMap<String, String>();

    Integer i; 
    String key,value;
    String myArray[] = this.param.split("&");


    for (i=0;i<myArray.length;i++){

        key=myArray[i].substring(0,myArray[i].indexOf("="));
        value=myArray[i].substring(myArray[i].indexOf("=")+1);
        this.hashmap.put(key,value);
    }
}

public String getParameterValue(String key){
    return this.hashmap.get(key);
}

public String getParam() {
    return param;
}

public void setParam(String param) {
    this.param = param;
}

public HashMap<String, String> getHashmap() {
    return hashmap;
}

public void setHashmap(HashMap<String, String> hashmap) {

    this.hashmap = hashmap;
}

}

When I Test the above method in case the URL is "param2=ffffhhh&param1=oooo&param3=pppp&param4=iiii&param5=kkkkk"

The result is: SIZE 5 URL param2=ffffhhh&param1=oooo&param3=pppp&param4=iiii&param5=kkkkk HASHMAP {param1=oooo, param2=ffffhhh, param3=pppp, param4=iiii, param5=kkkkk} PARAM1 = oooo

哪个是正确的

  public static void main(String[] args) {
    RequestParameter reqParam = new RequestParameter("param2=ffffhhh&param1=oooo&param3=pppp&param4=iiii&param5=kkkkk");
    System.out.println("SIZE " + reqParam.getHashmap().size());
    System.out.println("URL " + reqParam.getParam());
    System.out.println("HASHMAP " + reqParam.getHashmap());
    System.out.println("PARAM1 = " reqParam.getParameterValue("param1"));

}

but In case I pass the URL as the following one: "param2=ffff&&&hhh=&param1=oooo=&&param3=pppp&param4=iiii&&yy=&param5=kkkkk"

public static void main(String[] args) {
    RequestParameter reqParam = new RequestParameter("param2=ffff&&&hhh=&param1=oooo=&&param3=pppp&param4=iiii&&yy=&param5=kkkkk");
    System.out.println("SIZE " + reqParam.getHashmap().size());
    System.out.println("URL " + reqParam.getParam());
    System.out.println("HASHMAP " + reqParam.getHashmap());
    System.out.println("PARAM1 = " reqParam.getParameterValue("param1"));

}

它抛出以下异常:线程异常 "main" java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1 在 java.lang.String.substring(String.java:1937) 在 com.bml.icbs.ws.param.RequestParameter.(RequestParameter.java:188) 在 com.bml.icbs.ws.param.main.main(main.java:9)

确保数组元素 !empy.

for (i=0;i<myArray.length;i++){
        if(myArray[i] == null || myArray[i].length()==0){
                continue;
        }
        key=myArray[i].substring(0,myArray[i].indexOf("="));
        value=myArray[i].substring(myArray[i].indexOf("=")+1);
        this.hashmap.put(key,value);
    }