Java中URL的處理方法詳解
前言
URL(Uniform Resource Locator)中文名為統(tǒng)一資源定位符,有時(shí)也被俗稱為網(wǎng)頁(yè)地址。表示為互聯(lián)網(wǎng)上的資源,如網(wǎng)頁(yè)或者 FTP 地址。URL 可以分為如下幾個(gè)部分:
protocol://host:port/path?query#fragment
其中 protocol 表示協(xié)議,可以是 HTTP、HTTPS、FTP 和 File;host 表示主機(jī)名;port 表示端口號(hào);path 表示文件路徑及文件名。
一個(gè) Http 協(xié)議的 URL 實(shí)例如下:
http://www.runoob.com/index.html?language=cn#j2se
該 URL 實(shí)例 可以被解析為:
- 協(xié)議為(protocol):
http
- 主機(jī)為(host:port):
www.runoob.com
- 端口號(hào)為(port):
80
,以上URL實(shí)例并未指定端口,因?yàn)?HTTP 協(xié)議默認(rèn)的端口號(hào)為 80。 - 文件路徑為(path):
/index.html
- 請(qǐng)求參數(shù)(query):
language=cn
- 定位位置(fragment):
j2se
,定位到網(wǎng)頁(yè)中 id 屬性為 j2se 的 HTML 元素位置 。
URL 類(lèi)方法
在java.net包中定義了URL類(lèi),該類(lèi)用來(lái)處理有關(guān)URL的內(nèi)容。java.net.URL提供的 URL 構(gòu)建方式如下:
序號(hào) | 方法描述 |
---|---|
1 | public URL(String protocol, String host, int port, String file) throws MalformedURLException,通過(guò)給定的參數(shù)(協(xié)議、主機(jī)名、端口號(hào)、文件名)創(chuàng)建URL |
2 | public URL(String protocol, String host, String file) throws MalformedURLException,使用指定的協(xié)議、主機(jī)名、文件名創(chuàng)建URL,端口使用協(xié)議的默認(rèn)端口 |
3 | public URL(String url) throws MalformedURLException,通過(guò)給定的URL字符串創(chuàng)建URL |
4 | public URL(URL context, String url) throws MalformedURLException,使用基地址和相對(duì)URL創(chuàng)建 |
URL類(lèi)中包含了很多方法用于訪問(wèn)URL的各個(gè)部分,具體方法及描述如下:
序號(hào) | 方法描述 |
---|---|
1 | public String getPath(),返回URL路徑部分 |
2 | public String getQuery(),返回URL查詢部分 |
3 | public String getAuthority(),獲取此 URL 的授權(quán)部分 |
4 | public int getPort(),返回URL端口部分 |
5 | public int getDefaultPort(),返回協(xié)議的默認(rèn)端口號(hào) |
6 | public String getProtocol(),返回URL的協(xié)議 |
7 | public String getHost(),返回URL的主機(jī) |
8 | public String getFile(),返回URL文件名部分 |
9 | public String getRef(),獲取此 URL 的錨點(diǎn)(也稱為"引用") |
10 | public URLConnection openConnection() throws IOException,打開(kāi)一個(gè)URL連接,并運(yùn)行客戶端訪問(wèn)資源 |
URLConnections 類(lèi)方法
URL 的 openConnection() 方法返回一個(gè) java.net.URLConnection,該實(shí)例表示與URL 引用的遠(yuǎn)程對(duì)象的連接。例如:
- 如果你連接HTTP協(xié)議的URL, openConnection() 方法返回 HttpURLConnection 對(duì)象。
- 如果你連接的URL為一個(gè) JAR 文件, openConnection() 方法將返回 JarURLConnection 對(duì)象。
- 等等...
URLConnection 方法列表如下:
序號(hào) | 方法描述 |
---|---|
1 | Object getContent() ,檢索URL鏈接內(nèi)容 |
2 | Object getContent(Class[] classes) ,檢索URL鏈接內(nèi)容 |
3 | String getContentEncoding() ,返回頭部 content-encoding 字段值 |
4 | int getContentLength() ,返回頭部 content-length字段值 |
5 | String getContentType() ,返回頭部 content-type 字段值 |
6 | int getLastModified() ,返回頭部 last-modified 字段值 |
7 | long getExpiration() ,返回頭部 expires 字段值 |
8 | long getIfModifiedSince() ,返回對(duì)象的 ifModifiedSince 字段值 |
9 | public void setDoInput(boolean input),URL 連接可用于輸入和/或輸出。如果打算使用 URL 連接進(jìn)行輸入,則將 DoInput 標(biāo)志設(shè)置為 true;如果不打算使用,則設(shè)置為 false。默認(rèn)值為 true |
10 | public void setDoOutput(boolean output),URL 連接可用于輸入和/或輸出。如果打算使用 URL 連接進(jìn)行輸出,則將 DoOutput 標(biāo)志設(shè)置為 true;如果不打算使用,則設(shè)置為 false。默認(rèn)值為 false |
11 | public InputStream getInputStream() throws IOException,返回URL的輸入流,用于讀取資源 |
12 | public OutputStream getOutputStream() throws IOException,返回URL的輸出流, 用于寫(xiě)入資源 |
13 | public URL getURL(),返回 URLConnection 對(duì)象連接的URL |
方法實(shí)例
獲取URL的各個(gè)部分參數(shù)
public class Test { public static void main(String[] args) { try { URL url = new URL("http://www.juejin.cn/index.html?language=cn#j2se"); System.out.println("URL 為:" + url.toString()); System.out.println("協(xié)議為:" + url.getProtocol()); System.out.println("驗(yàn)證信息:" + url.getAuthority()); System.out.println("文件名及請(qǐng)求參數(shù):" + url.getFile()); System.out.println("主機(jī)名:" + url.getHost()); System.out.println("路徑:" + url.getPath()); System.out.println("端口:" + url.getPort()); System.out.println("默認(rèn)端口:" + url.getDefaultPort()); System.out.println("請(qǐng)求參數(shù):" + url.getQuery()); System.out.println("定位位置:" + url.getRef()); }catch(IOException e) { e.printStackTrace(); } } } ???????// 以上程序執(zhí)行結(jié)果為: // URL 為:http://www.juejin.cn/index.html?language=cn#j2se // 協(xié)議為:http // 驗(yàn)證信息:www.juejin.cn // 文件名及請(qǐng)求參數(shù):/index.html?language=cn // 主機(jī)名:www.juejin.cn // 路徑:/index.html // 端口:-1 // 默認(rèn)端口:80 // 請(qǐng)求參數(shù):language=cn // 定位位置:j2se
URL采用了HTTP 協(xié)議時(shí),openConnection 返回HttpURLConnection對(duì)象
public class Test { public static void main(String[] args) { try { URL url = new URL("https://juejin.cn"); URLConnection urlConnection = url.openConnection(); HttpURLConnection connection = null; if(urlConnection instanceof HttpURLConnection) { connection = (HttpURLConnection) urlConnection; } else { System.out.println("請(qǐng)輸入 URL 地址"); return; } BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String urlString = ""; String current; while((current = in.readLine()) != null) { urlString += current; } System.out.println(urlString); }catch(IOException e) { e.printStackTrace(); } } } // 以上程序執(zhí)行結(jié)果為: // <!doctype html><html data-n-head-ssr lang="zh" data-n-head="%7B%22lang%22:%7B%22ssr%22:%22zh%22%7D%7D"> <head > <title>稀土掘金</title>...
獲取遠(yuǎn)程文件大小
public class Test { public static void main(String[] args) throws Exception { int size; URL url = new URL("https://juejin.cn"); // 獲取 URLConnection 實(shí)例 URLConnection conn = url.openConnection(); // 獲取頭部 content-length 字段值 size = conn.getContentLength(); if (size < 0) System.out.println("無(wú)法獲取文件大小。"); else { System.out.println("文件大小為:" + size + " bytes"); } // 關(guān)閉輸入流 conn.getInputStream().close(); } } ???????// 以上程序執(zhí)行結(jié)果為: // 文件大小為:84127 bytes
網(wǎng)頁(yè)抓取
public class Test { public static void main(String[] args) throws Exception { URL url = new URL("https://juejin.cn"); // 打開(kāi)一個(gè)到此 URL 的連接,并返回一個(gè) InputStream,將 InputStream 轉(zhuǎn)為緩沖字符輸入流 BufferedReader reader = new BufferedReader (new InputStreamReader(url.openStream())); // 創(chuàng)建指定文件的字符輸出流 BufferedWriter writer = new BufferedWriter (new FileWriter("data.html")); String line; // 將讀取內(nèi)容寫(xiě)入文件 while ((line = reader.readLine()) != null) { System.out.println(line); writer.write(line); writer.newLine(); } // 關(guān)閉流 reader.close(); writer.close(); } } ???????// 以上程序執(zhí)行結(jié)果為: // 網(wǎng)頁(yè)的源代碼,存儲(chǔ)在當(dāng)前目錄下的 data.html 文件中
獲取 URL 響應(yīng)頭的日期信息
public class Test { public static void main(String[] args) throws Exception { URL url = new URL("https://juejin.cn"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); // 獲取頭部日期字段的值 long date = httpCon.getDate(); if (date == 0) { System.out.println("無(wú)法獲取信息。"); } else { System.out.println("Date: " + new Date(date)); } } } // 以上程序執(zhí)行結(jié)果為: // Date: Thu May 11 22:32:04 CST 2023
獲取 URL 響應(yīng)頭信息
public class Test { public static void main(String[] args) throws Exception { URL url = new URL("http://www.runoob.com"); URLConnection conn = url.openConnection(); // 獲取頭部字段的不可修改映射 Map headers = conn.getHeaderFields(); // 遍歷頭部字段映射鍵值 Set<String> keys = headers.keySet(); for( String key : keys ){ String val = conn.getHeaderField(key); System.out.println(key+" "+val); } System.out.println( conn.getLastModified() ); } } ???????// 以上程序執(zhí)行結(jié)果為: // null HTTP/1.1 302 Moved Temporarily // X-Cache-Status MISS // Server JSP3/2.0.14 // Connection keep-alive // Content-Length 144 // Date Thu, 11 May 2023 14:37:51 GMT // Location https://www.runoob.com/ // Content-Type text/html // 0
查看主機(jī)指定文件的最后修改時(shí)間
public class Test { public static void main(String[] args) throws Exception { URL u = new URL("https://static.runoob.com/assets/upvotejs/dist/upvotejs/upvotejs.vanilla.js"); URLConnection uc = u.openConnection(); SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss"); // 將此 URLConnection 的 useCaches 字段的值設(shè)置為 false 以忽略緩存 uc.setUseCaches(false); // 獲取文件最后修改時(shí)間 long timestamp = uc.getLastModified(); System.out.println("vanilla.js 文件最后修改時(shí)間 :" + ft.format(new Date(timestamp))); } } // 以上程序執(zhí)行結(jié)果為: // vanilla.js 文件最后修改時(shí)間 :2019-08-01 06:23:35
到此這篇關(guān)于Java中URL的處理方法詳解的文章就介紹到這了,更多相關(guān)Java URL處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring 實(shí)現(xiàn)excel及pdf導(dǎo)出表格示例
本篇文章主要介紹了Spring 實(shí)現(xiàn)excel及pdf導(dǎo)出表格示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-03-03詳解SpringBoot+Thymeleaf 基于HTML5的現(xiàn)代模板引擎
本篇文章主要介紹了SpringBoot+Thymeleaf 基于HTML5的現(xiàn)代模板引擎,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10Spring Boot產(chǎn)生環(huán)形注入的解決方案
這篇文章主要介紹了Spring Boot產(chǎn)生環(huán)形注入的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09mybatis多對(duì)多關(guān)聯(lián)實(shí)戰(zhàn)教程(推薦)
下面小編就為大家?guī)?lái)一篇mybatis多對(duì)多關(guān)聯(lián)實(shí)戰(zhàn)教程(推薦)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-10-10java線程并發(fā)控制同步工具CountDownLatch
這篇文章主要為大家介紹了java線程并發(fā)控制同步工具CountDownLatch使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08Spring?Boot整合?NoSQL?數(shù)據(jù)庫(kù)?Redis詳解
這篇文章主要為大家介紹了Spring?Boot整合?NoSQL?數(shù)據(jù)庫(kù)?Redis詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09Spring Boot加密配置文件特殊內(nèi)容的示例代碼詳解
這篇文章主要介紹了Spring Boot加密配置文件特殊內(nèi)容的相關(guān)知識(shí),本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-05-05