如果有不明智的字符,如何将URL转换为URI? [英] How to convert URL toURI when there are unwise characters?

查看:113
本文介绍了如果有不明智的字符,如何将URL转换为URI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个URL对象,其路径包含不明智的字符(RFC 2396)就我而言是| (管)字符。
现在我需要安全地将其转换为URI,但 URL.toURI() 会抛出异常。

I've got URL object with path containing unwise characters (RFC 2396) in my case it is "|" (pipe) character. Now I need to safely convert that to URI, but URL.toURI() throws an exception.

我读过 URL文档但这部分让我感到困惑:

I've read URL documentation but this part is for me confusing:


根据RFC2396中定义的转义机制,URL类本身不会对任何URL组件
进行编码或解码。调用者的
责任是对任何字段进行编码,这些字段需要在调用URL之前进行
转义,并且还要解码从URL返回的任何转义字段
。此外,由于URL不知道URL转义的
,因此它无法识别编码的
或同一URL的解码形式之间的等效性。

The URL class does not itself encode or decode any URL components according to the escaping mechanism defined in RFC2396. It is the responsibility of the caller to encode any fields, which need to be escaped prior to calling URL, and also to decode any escaped fields, that are returned from URL. Furthermore, because URL has no knowledge of URL escaping, it does not recognize equivalence between the encoded or decoded form of the same URL.

那我该怎么做呢?在转换过程中对此字符进行编码的模式是什么?我是否需要创建我的URL对象的编码副本?

So how should I do it? What is the pattern here to encode this characters during conversion? Do I need create encoded copy of my URL object?

推荐答案

好的,我想出这样的事情:

OK, I come up with something like this:

URI uri = new URI(url.getProtocol(), 
                  null /*userInfo*/,
                  url.getHost(), 
                  url.getPort(), 
                  (url.getPath()==null)?null:URLDecoder.decode(url.getPath(), "UTF-8"),
                  (url.getQuery()==null)?null:URLDecoder.decode(url.getQuery(), "UTF-8"),
                  null /*fragment*/);

看起来很有效,这是一个例子。有人可以确认这是正确的解决方案吗?

Looks like it works, here is an example. Can some one confirm that this is proper solution?

编辑初始解决方案出现了一些问题,所以我已修复它。

Edit: initial solution had some problems when there was a query so I've fixed it.

这篇关于如果有不明智的字符,如何将URL转换为URI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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