编码 URL 查询参数 [英] Encode URL query parameters

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

问题描述

如何对 URL 查询参数值进行编码?我需要用 %20、重音、非 ASCII 字符等替换空格.

How can I encode URL query parameter values? I need to replace spaces with %20, accents, non-ASCII characters etc.

我尝试使用 URLEncoder 但它也对 / 字符进行编码,如果我将用 URLEncoder 编码的字符串提供给 URL 构造函数,我会得到MalformedURLException(无协议).

I tried to use URLEncoder but it also encodes / character and if I give a string encoded with URLEncoder to the URL constructor I get a MalformedURLException (no protocol).

推荐答案

URLEncoder 有一个很误导性的名字.它是根据 Javadocs 使用的编码使用 MIME 类型 application/x-www-form-urlencoded 的表单参数.

URLEncoder has a very misleading name. It is according to the Javadocs used encode form parameters using MIME type application/x-www-form-urlencoded.

话虽如此,它可用于编码,例如,查询参数.例如,如果一个参数看起来像 &/?#,它的编码等价物可以用作:

With this said it can be used to encode e.g., query parameters. For instance if a parameter looks like &/?# its encoded equivalent can be used as:

String url = "http://host.com/?key=" + URLEncoder.encode("&/?#");

<小时>

除非您有这些特殊需求,URL javadocs 建议使用 new URI(..).toURL它根据 RFC2396 执行 URI 编码.


Unless you have those special needs the URL javadocs suggests using new URI(..).toURL which performs URI encoding according to RFC2396.

管理 URL 编码和解码的推荐方式是使用 URI

The recommended way to manage the encoding and decoding of URLs is to use URI

以下示例

new URI("http", "host.com", "/path/", "key=| ?/#ä", "fragment").toURL();

产生结果 http://host.com/path/?key=%7C%20?/%23ä#fragment.请注意诸如 ?&/ 之类的字符是如何编码的.

produces the result http://host.com/path/?key=%7C%20?/%23ä#fragment. Note how characters such as ?&/ are not encoded.

有关更多信息,请参阅帖子 Java 中的 HTTP URL 地址编码如何编码 URL 以避免 java 中的特殊字符.

For further information, see the posts HTTP URL Address Encoding in Java or how to encode URL to avoid special characters in java.

编辑

由于您的输入是字符串 URL,因此使用 URI 的参数化构造函数之一将无济于事.您也不能直接使用 new URI(strUrl),因为它不引用 URL 参数.

Since your input is a string URL, using one of the parameterized constructor of URI will not help you. Neither can you use new URI(strUrl) directly since it doesn't quote URL parameters.

所以在这个阶段我们必须使用一个技巧来得到你想要的:

So at this stage we must use a trick to get what you want:

public URL parseUrl(String s) throws Exception {
     URL u = new URL(s);
     return new URI(
            u.getProtocol(), 
            u.getAuthority(), 
            u.getPath(),
            u.getQuery(), 
            u.getRef()).
            toURL();
}

在您可以使用此例程之前,您必须清理您的字符串以确保它代表一个绝对 URL.我看到了两种方法:

Before you can use this routine you have to sanitize your string to ensure it represents an absolute URL. I see two approaches to this:

  1. 猜测.将 http:// 前置到字符串,除非它已经存在.

  1. Guessing. Prepend http:// to the string unless it's already present.

使用 新的 URL(URL 上下文,字符串规范)

这篇关于编码 URL 查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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