Java中URL的處理方法詳解
前言
URL(Uniform Resource Locator)中文名為統(tǒng)一資源定位符,有時也被俗稱為網(wǎng)頁地址。表示為互聯(lián)網(wǎng)上的資源,如網(wǎng)頁或者 FTP 地址。URL 可以分為如下幾個部分:
protocol://host:port/path?query#fragment
其中 protocol 表示協(xié)議,可以是 HTTP、HTTPS、FTP 和 File;host 表示主機名;port 表示端口號;path 表示文件路徑及文件名。
一個 Http 協(xié)議的 URL 實例如下:
http://www.runoob.com/index.html?language=cn#j2se
該 URL 實例 可以被解析為:
- 協(xié)議為(protocol):
http
- 主機為(host:port):
www.runoob.com
- 端口號為(port):
80
,以上URL實例并未指定端口,因為 HTTP 協(xié)議默認的端口號為 80。 - 文件路徑為(path):
/index.html
- 請求參數(shù)(query):
language=cn
- 定位位置(fragment):
j2se
,定位到網(wǎng)頁中 id 屬性為 j2se 的 HTML 元素位置 。
URL 類方法
在java.net包中定義了URL類,該類用來處理有關URL的內容。java.net.URL提供的 URL 構建方式如下:
序號 | 方法描述 |
---|---|
1 | public URL(String protocol, String host, int port, String file) throws MalformedURLException,通過給定的參數(shù)(協(xié)議、主機名、端口號、文件名)創(chuàng)建URL |
2 | public URL(String protocol, String host, String file) throws MalformedURLException,使用指定的協(xié)議、主機名、文件名創(chuàng)建URL,端口使用協(xié)議的默認端口 |
3 | public URL(String url) throws MalformedURLException,通過給定的URL字符串創(chuàng)建URL |
4 | public URL(URL context, String url) throws MalformedURLException,使用基地址和相對URL創(chuàng)建 |
URL類中包含了很多方法用于訪問URL的各個部分,具體方法及描述如下:
序號 | 方法描述 |
---|---|
1 | public String getPath(),返回URL路徑部分 |
2 | public String getQuery(),返回URL查詢部分 |
3 | public String getAuthority(),獲取此 URL 的授權部分 |
4 | public int getPort(),返回URL端口部分 |
5 | public int getDefaultPort(),返回協(xié)議的默認端口號 |
6 | public String getProtocol(),返回URL的協(xié)議 |
7 | public String getHost(),返回URL的主機 |
8 | public String getFile(),返回URL文件名部分 |
9 | public String getRef(),獲取此 URL 的錨點(也稱為"引用") |
10 | public URLConnection openConnection() throws IOException,打開一個URL連接,并運行客戶端訪問資源 |
URLConnections 類方法
URL 的 openConnection() 方法返回一個 java.net.URLConnection,該實例表示與URL 引用的遠程對象的連接。例如:
- 如果你連接HTTP協(xié)議的URL, openConnection() 方法返回 HttpURLConnection 對象。
- 如果你連接的URL為一個 JAR 文件, openConnection() 方法將返回 JarURLConnection 對象。
- 等等...
URLConnection 方法列表如下:
序號 | 方法描述 |
---|---|
1 | Object getContent() ,檢索URL鏈接內容 |
2 | Object getContent(Class[] classes) ,檢索URL鏈接內容 |
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() ,返回對象的 ifModifiedSince 字段值 |
9 | public void setDoInput(boolean input),URL 連接可用于輸入和/或輸出。如果打算使用 URL 連接進行輸入,則將 DoInput 標志設置為 true;如果不打算使用,則設置為 false。默認值為 true |
10 | public void setDoOutput(boolean output),URL 連接可用于輸入和/或輸出。如果打算使用 URL 連接進行輸出,則將 DoOutput 標志設置為 true;如果不打算使用,則設置為 false。默認值為 false |
11 | public InputStream getInputStream() throws IOException,返回URL的輸入流,用于讀取資源 |
12 | public OutputStream getOutputStream() throws IOException,返回URL的輸出流, 用于寫入資源 |
13 | public URL getURL(),返回 URLConnection 對象連接的URL |
方法實例
獲取URL的各個部分參數(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("驗證信息:" + url.getAuthority()); System.out.println("文件名及請求參數(shù):" + url.getFile()); System.out.println("主機名:" + url.getHost()); System.out.println("路徑:" + url.getPath()); System.out.println("端口:" + url.getPort()); System.out.println("默認端口:" + url.getDefaultPort()); System.out.println("請求參數(shù):" + url.getQuery()); System.out.println("定位位置:" + url.getRef()); }catch(IOException e) { e.printStackTrace(); } } } ???????// 以上程序執(zhí)行結果為: // URL 為:http://www.juejin.cn/index.html?language=cn#j2se // 協(xié)議為:http // 驗證信息:www.juejin.cn // 文件名及請求參數(shù):/index.html?language=cn // 主機名:www.juejin.cn // 路徑:/index.html // 端口:-1 // 默認端口:80 // 請求參數(shù):language=cn // 定位位置:j2se
URL采用了HTTP 協(xié)議時,openConnection 返回HttpURLConnection對象
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("請輸入 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í)行結果為: // <!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>...
獲取遠程文件大小
public class Test { public static void main(String[] args) throws Exception { int size; URL url = new URL("https://juejin.cn"); // 獲取 URLConnection 實例 URLConnection conn = url.openConnection(); // 獲取頭部 content-length 字段值 size = conn.getContentLength(); if (size < 0) System.out.println("無法獲取文件大小。"); else { System.out.println("文件大小為:" + size + " bytes"); } // 關閉輸入流 conn.getInputStream().close(); } } ???????// 以上程序執(zhí)行結果為: // 文件大小為:84127 bytes
網(wǎng)頁抓取
public class Test { public static void main(String[] args) throws Exception { URL url = new URL("https://juejin.cn"); // 打開一個到此 URL 的連接,并返回一個 InputStream,將 InputStream 轉為緩沖字符輸入流 BufferedReader reader = new BufferedReader (new InputStreamReader(url.openStream())); // 創(chuàng)建指定文件的字符輸出流 BufferedWriter writer = new BufferedWriter (new FileWriter("data.html")); String line; // 將讀取內容寫入文件 while ((line = reader.readLine()) != null) { System.out.println(line); writer.write(line); writer.newLine(); } // 關閉流 reader.close(); writer.close(); } } ???????// 以上程序執(zhí)行結果為: // 網(wǎng)頁的源代碼,存儲在當前目錄下的 data.html 文件中
獲取 URL 響應頭的日期信息
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("無法獲取信息。"); } else { System.out.println("Date: " + new Date(date)); } } } // 以上程序執(zhí)行結果為: // Date: Thu May 11 22:32:04 CST 2023
獲取 URL 響應頭信息
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í)行結果為: // 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
查看主機指定文件的最后修改時間
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 字段的值設置為 false 以忽略緩存 uc.setUseCaches(false); // 獲取文件最后修改時間 long timestamp = uc.getLastModified(); System.out.println("vanilla.js 文件最后修改時間 :" + ft.format(new Date(timestamp))); } } // 以上程序執(zhí)行結果為: // vanilla.js 文件最后修改時間 :2019-08-01 06:23:35
到此這篇關于Java中URL的處理方法詳解的文章就介紹到這了,更多相關Java URL處理內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring 實現(xiàn)excel及pdf導出表格示例
本篇文章主要介紹了Spring 實現(xiàn)excel及pdf導出表格示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03詳解SpringBoot+Thymeleaf 基于HTML5的現(xiàn)代模板引擎
本篇文章主要介紹了SpringBoot+Thymeleaf 基于HTML5的現(xiàn)代模板引擎,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10Spring Boot產(chǎn)生環(huán)形注入的解決方案
這篇文章主要介紹了Spring Boot產(chǎn)生環(huán)形注入的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09mybatis多對多關聯(lián)實戰(zhàn)教程(推薦)
下面小編就為大家?guī)硪黄猰ybatis多對多關聯(lián)實戰(zhàn)教程(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10java線程并發(fā)控制同步工具CountDownLatch
這篇文章主要為大家介紹了java線程并發(fā)控制同步工具CountDownLatch使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08Spring?Boot整合?NoSQL?數(shù)據(jù)庫?Redis詳解
這篇文章主要為大家介紹了Spring?Boot整合?NoSQL?數(shù)據(jù)庫?Redis詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09