在 Android 上解析查询字符串 [英] Parsing query strings on Android

查看:40
本文介绍了在 Android 上解析查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java EE 有 ServletRequest.getParameterValues().

Java EE has ServletRequest.getParameterValues().

在非 EE 平台上,URL.getQuery() 只返回一个字符串.

On non-EE platforms, URL.getQuery() simply returns a string.

不是在 Java EE 上时,正确解析 URL 中的查询字符串的正常方法是什么?

What's the normal way to properly parse the query string in a URL when not on Java EE?

尝试制作自己的解析器在答案中很受欢迎.这是一个非常有趣和令人兴奋的微编码项目,但是我不能说这是一个好主意.

It is popular in the answers to try and make your own parser. This is very interesting and exciting micro-coding project, but I cannot say that it is a good idea.

下面的代码片段通常有缺陷或损坏.打破它们对读者来说是一个有趣的练习.以及攻击使用它们的网站的黑客.

The code snippets below are generally flawed or broken. Breaking them is an interesting exercise for the reader. And to the hackers attacking the websites that use them.

解析查询字符串是一个定义明确的问题,但阅读规范并理解细微差别并非易事.最好让一些平台库编码员为你做艰苦的工作,并为你做修复!

Parsing query strings is a well defined problem but reading the spec and understanding the nuances is non-trivial. It is far better to let some platform library coder do the hard work, and do the fixing, for you!

推荐答案

自从 Android M 以来,事情变得更加复杂.android.net 的答案.URI.getQueryParameter() 有一个错误,它在 JellyBean 之前破坏了空格.Apache URLEncodedUtils.parse() 工作,但 已在 L 中弃用在 M 中删除.

Since Android M things have got more complicated. The answer of android.net.URI.getQueryParameter() has a bug which breaks spaces before JellyBean. Apache URLEncodedUtils.parse() worked, but was deprecated in L, and removed in M.

所以现在最好的答案是 UrlQuerySanitizer.这从 API 级别 1 开始就存在并且仍然存在.它还让您思考如何处理特殊字符或重复值等棘手问题.

So the best answer now is UrlQuerySanitizer. This has existed since API level 1 and still exists. It also makes you think about the tricky issues like how do you handle special characters, or repeated values.

最简单的代码是

UrlQuerySanitizer.ValueSanitizer sanitizer = UrlQuerySanitizer.getAllButNullLegal();
// remember to decide if you want the first or last parameter with the same name
// If you want the first call setPreferFirstRepeatedParameter(true);
sanitizer.parseUrl(url);
String value = sanitizer.getValue("paramName");

如果您对默认解析行为感到满意,可以执行以下操作:

If you are happy with the default parsing behavior you can do:

new UrlQuerySanitizer(url).getValue("paramName")

但是您应该确保您了解默认解析行为是什么,因为它可能不是您想要的.

but you should make sure you understand what the default parsing behavor is, as it might not be what you want.

这篇关于在 Android 上解析查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆