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

查看:79
本文介绍了编码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建议使用 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秒登录
发送“验证码”获取 | 15天全站免登陆