将字符串解析为URL [英] Parse string to URL

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

问题描述

如何解析动态字符串值以创建URL实例?我需要用%20 替换空格,重音符号,非ASCII字符......?

How can I parse dynamic string values in order to create URL instances? I need to replace spaces with %20, accents, non-ASCII characters...?

我试过使用 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 建议使用 新URI(..)。toURL 根据<执行URI编码a 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上下文,字符串规范)

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

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