简体   繁体   English

从Java中的查询字符串中提取参数及其值

[英]Extract parameters and their values from query string in Java

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? 在Java中解析这个问题的最佳方法是什么? So far I could not found a solution with standard Java libraries, and I don't want to reinvent the wheel. 到目前为止,我找不到标准Java库的解决方案,我不想重新发明轮子。

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());
}

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 .*\\\\? 例如像这样一个".*\\\\?param1=(.*)&param2=(.*)&param3=(.*)$"这适用于您的网址示例,这就是我添加.*\\\\? 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=(.*)$ 这将适用于第一个样本( "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 当然,如果你的params名字也不是你不知道的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM