Extract parameters and their values from query string in Java

坚强是说给别人听的谎言 提交于 2020-02-12 04:09:09

问题


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:


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



来源:https://stackoverflow.com/questions/27445722/extract-parameters-and-their-values-from-query-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!