URL 获取网络资源

[size=medium][b]URL 获取网络资源[/b][/size]

package com.itheima.net;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

public class TextURL {

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String imageFile="http://www.iteye.com/upload/logo/user/715302/3e63bcb1-8e77-369f-9e65-e97017c47322.jpg?1343613979";
String htmlFile="http://takeme.iteye.com/";
String host="http://www.iteye.com/";
String file="/index.html";
System.out.println("===============1.获取URL指定图像资源信息");
getImageResourceByURL(imageFile);
System.out.println("===============2.获取URL指定的HTML资源信息");
getHtmlResourceByURL(htmlFile);
System.out.println("===============3.根据URL创建读对象读取网页内容");
getHTMLResouce(htmlFile);
System.out.println("===============4.根据URL创建输入流读取网页内容");
getResourceOfHtml(htmlFile);
System.out.println("===============5.判断Java所支持的URL类型");
supportURLType(host, file);
}

public static void getImageResourceByURL(String imageFile) throws Exception{
URL url=new URL(imageFile);
Object obj=url.getContent(); //获得此URL的内容
System.out.println(obj.getClass().getName());//显示名称
}
//根据制定的URL获取资源
public static void getHtmlResourceByURL(String htmlFile) throws Exception{
URL url=new URL(htmlFile);
URLConnection uc=url.openConnection(); //创建远程对象的连接对象
uc.setRequestProperty("Charset", "UTF-8"); //好像没有用
InputStream in=uc.getInputStream(); //打开连接 读取输入流

int c;
while ((c=in.read())!=-1) {
System.out.print((char)c);
}
System.out.println();
in.close();
}

//读取URL指定的网页内容
public static void getHTMLResouce(String htmlFile) throws Exception{
URL url=new URL(htmlFile);
Reader reader=new InputStreamReader(new BufferedInputStream(url.openStream()),"UTF-8");
int c;
while ((c=reader.read())!=-1) {
System.out.print((char)c);

}
System.out.println();
reader.close();

}
//读取URL制定的网页内容
public static void getResourceOfHtml(String htmlFile) throws Exception{
URL url=new URL(htmlFile);

InputStream in =url.openStream();
int c;
while ((c=in.read())!=-1) {
System.out.print((char)c);
}
System.out.println();
in.close();
}

public static void supportURLType(String host,String file){
String [] schemes={"http","https","ftp","mailto","telnet","file","ldap",
"gopher","jdbc","rmi","jndi","jar","doc","netdoc","nfs","verbatim","finger","daytime","systemrecource"};
for (int i = 0; i < schemes.length; i++) {
try {
URL u=new URL(schemes[i],host,file);
System.out.println(schemes[i]+"是java所支持的URL类型\r\n");
} catch (Exception e) {
System.out.println(schemes[i]+"不是java所支持的URL类型\r\n");
}
}


}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值