日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java解析url字符串,将字符串解析为URL

發布時間:2024/1/23 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java解析url字符串,将字符串解析为URL 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

How can I parse 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 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("&/?#");

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

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

The following sample

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

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

EDIT

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:

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

Construct the URI from a context using new URL(URL context, String spec)

總結

以上是生活随笔為你收集整理的java解析url字符串,将字符串解析为URL的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。