根据url获取html源码,通过URL访问和获取html源代码
Uniform Resource Locator ,在Internet的WWW服務(wù)程序上用于指定信息位置的表示方法
指定互聯(lián)網(wǎng)或本地上(web服務(wù)中)的文件、對象資源 等,或者說它相當(dāng)于一個互聯(lián)網(wǎng)上資源的一個指針
協(xié)議??????????? 主機? 路徑??? 資源
http://www.itfuture.org/forum/index.jsp??? ?? url
(1)URL url = getServletContext().getResource(path);
由ServletContext上下文對象可以得到該servlet所運行web容器中的一些資源,
通過傳遞資源的相對路徑來獲得相應(yīng)的資源,要求該路徑必須是針對servlet的一個相對路徑,該相對路徑必須以”/”開頭
url.toExternalForm()?? jndi:/localhost/MvcFrame/WEB-INF/itfuture-config.xml
url.toString()???????? jndi:/localhost/MvcFrame/WEB-INF/itfuture-config.xml
構(gòu)造(獲得)該url的字符串形式的表示
url.openStream();
表示:打開到url定位的資源的連接,并返回通過該連接,所連接到資源的InputStream,
可以通過該InputStream讀該資源的Content,讀資源以字節(jié)形式來讀
jndi
java naming & direction interface
jndi根目錄中保存了大量的jndi
每一個jndi和一個資源或者對象一一對應(yīng)
“jndi:”,表示以在web容器中的jndi目錄中以資源唯一的jndi的方法來查找到對應(yīng)資源
(2) URL url=getClass().getResource(“/org/itfuture/www/ApplicationResources”);
必須依賴于Class Loader 來尋找進而動態(tài)導(dǎo)入該資源
如果一個資源在包中話適合用該方式
例子如下:
package org.itfuture.www.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
public class URLApp
{
void display()
{
byte buf[]=new byte[1000];
try
{
System.out.print("請輸入文件的URL地址:");
//讀取用戶輸入的URL
InputStream consoleis=System.in;
int count=consoleis.read(buf);
String addr=new String(buf,0,count);
//將用戶輸入的URL字符串傳入URL類對象
URL url=new URL (addr);
//創(chuàng)建URLConnection對象,用URL的openConnection方法將連接通過返回給URLConnection的對象
//實際上URL的openConnection的返回值就是一個URLConnection
URLConnection c = url.openConnection(); //*
//用URLConnection的connect()方法建立連接
c.connect();??????????????????????????? //*
// 顯示該連接的相關(guān)信息,這些都是URLConnection的方法
System.out.println("內(nèi)容類型: "+c.getContentType());
System.out.println("內(nèi)容長度: "+c.getContentLength());
System.out.println("創(chuàng)建日期: "+new Date(c.getDate()));
System.out.println("最后修改日期: "+new Date(c.getLastModified()));
System.out.println("終止日期: "+new Date(c.getExpiration()));
InputStream is=c.getInputStream();? //*
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
String str=null;
while((str=br.readLine())!=null)
{
System.out.println(str);
}
}catch(IOException e){
System.out.println(e);
}
}
public static void main(String[] args)
{
URLApp app=new URLApp();
app.display();
}
}
總結(jié)
以上是生活随笔為你收集整理的根据url获取html源码,通过URL访问和获取html源代码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 0.20风阻系数史上最低!奔驰全新车型预
- 下一篇: html2canvas改成同步,html