Extract parameters and their values from query str

2019-01-28 11:59发布

So let's suppose I have a string like

"param1=value1&param2={"url":"http://somesite.com?someparam=somevalue&someparam1=somevalue1"}&param3=value3"

and I need it to be:

param1: value1

param2: {"url":"http://somesite.com?someparam=somevalue&someparam1=somevalue1"}

param3: value3

What would be the best approach to parse this in Java? So far I could not found a solution with standard Java libraries, and I don't want to reinvent the wheel.

I've tried with (but it would not work if I put there only query parameters like mine):

String url = "http://www.example.com/something.html?one=11111&two=22222&three=33333";
List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), "UTF-8");

for (NameValuePair param : params) {
    System.out.println(param.getName() + " : " + param.getValue());
}

1条回答
老娘就宠你
2楼-- · 2019-01-28 12:28

Why don't you use something like a regex :

for example like this one ".*\\?param1=(.*)&param2=(.*)&param3=(.*)$" this works for your url sample that's why I added the .*\\? part ;)

and this will work for the first sample ("param1=value1&param2={"url":"http://somesite.com?someparam=somevalue&someparam1=somevalue1"}&param3=value3" --> param1=(.*)&param2=(.*)&param3=(.*)$

Of course if your params names aren't also something you don't know about

查看更多
登录 后发表回答