Java - 编码URL [英] Java - encode URL

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

问题描述

如何编码动态字符串值以创建URL实例?我需要用%20替换空格,口音,非ASCII字符...?
我试图使用URLEncoder,但它也会编码'/'字符,如果我给一个URLEncoder编码的字符串给URL构造函数,我得到一个MalformedURLException(没有协议)。

How can I encode dynamic String values in order to create URL instances? I need to replace spaces with %20, accents, non-ASCII characters... ? 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 建议使用 新的URI(..)toURL ,根据<一个href =http://www.ietf.org/rfc/rfc2396.txt =nofollow noreferrer> 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 /?%23A#片段。请注意,如?& / 之类的字符不会编码。

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 不会帮助您。你也不能直接使用新的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();
}

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

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上下文,String spec)

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

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