资源地址-URL类

1、URL类指定的是资源地址

InetAddress类指定的是网络地址

两者的粒度不一样

2、常用API1:InputStream URL.openStream()

功能:下载web页面

(若资源为非web页面,如图片,则输出乱码)

(没有调用http协议,用fiddler没有抓到http包)

该方法调用tcp协议,返回一个该url指向资源的输入流,读取输入流,可以得到文本String

该方法如下:

public static String getSource(String url){
StringBuilder sb=new StringBuilder();
InputStream in = null;
try {
// Open the URL for reading
URL u = new URL(url);
in = u.openStream();
// buffer the input to increase performance
in = new BufferedInputStream(in);
// chain the InputStream to a Reader
Reader r = new InputStreamReader(in);
int c;
while ((c = r.read()) != -1) {
sb.append((char) c);
}
} catch (MalformedURLException ex) {
System.err.println(url + " is not a parseable URL");
} catch (IOException ex) {
System.err.println(ex);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
}
return sb.toString();
}

测试:System.out.println(getSource("http://www.baidu.com"));

结果:<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=Edge"><meta content="always" name="referrer"><meta name="theme-color" content="#2932e1"><link rel="shortcut icon" href="/favicon.ico" type="image/x-

...........

(不包含http头)

3,、常用API2:URLConnection URL.openConnection()

该方法与服务器直接通信,打开一个socket后得到连接,其中服务器发送的数据格式不定(文本,图片,音频等)

4、常用API3:Object URL.getContent()

该方法得到服务器返回资源的数据格式,如 

图片:sun.awt.image.URLImageSource

文本:sun.net.www.protocol.http.HttpURLConnection$HttpInputStream

视频:sun.net.www.protocol.http.HttpURLConnection$HttpInputStream

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值