URL部分功能代码实现

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;


import org.junit.Test;


/*
 * URL  网络资源定位指针——URL类
 * url部分功能代码实现
 */
public class UrlDemo {
@Test
public void demo1(){
try {
URL url = new URL("http://www.baidu.com");
InputStream in = url.openStream();
//打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream。
BufferedReader br= new BufferedReader(
new InputStreamReader(in,"utf-8"));
String str = null;
while((str= br.readLine())!=null){
if(str.indexOf("百")>=0){
System.out.println("str="+str);
}
System.out.println(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}



// 2。☆URL的通信链接——URLConnection类
// 2.1public abstract class URLConnection{
//  public URL getURL()            //返回当前连接的URL对象
//  public int getContentLength()  //返回资源文件的长度
//  public String getContentType() //返回资源文件的类型
//  public long getLastModified()  //返回资源文件的最后修改日期
// }
// 2.2URL类的openConnection()方法可创建一个URLConnection对象
// public URLConnection openConnection()  throws IOException


@Test
public void demo2(){
try {
URL url = new URL("http://www.baidu.com");
URLConnection con = url.openConnection();
//返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。
Long lg = con.getDate();//服务器响应时间
System.out.println(getDatestr(lg));

Long lg2= con.getLastModified();
System.out.println(getDatestr(lg2));
} catch (IOException e) {

e.printStackTrace();
}

}
//控制时间的输出格式
private String getDatestr(long lg) {
Date d= new Date(lg);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
String strDate = sdf.format(d);
return strDate;
}




//3.☆互联网协议(IP)地址——InetAddress类
// public class InetAddress implements Serializable{
//  public static InetAddress getByName(String host)
//  public static InetAddress getByAddress(String host, byte[] addr)
//  public static InetAddress getLocalHost() //返回本地主机
//  public String getHostAddress()   //返回IP地址字符串
//  public String getHostName()     //返回主机名
// }
//InetAddress的实例对象包含以数字形式保存的IP地址,
//同时还可能包含主机名(如果使用主机名来获取InetAddress的实例,
//或者使用数字来构造,并且启用了反向主机名解析的功能)。
//InetAddress类提供了将主机名解析为IP地址(或反之)的方法。
@Test
public void demo3(){
try {
InetAddress ip = InetAddress.getByName("www.baidu.com");//InetAddress是Java对IP地址的封装
String ipAddr = ip.getHostAddress();//返回 IP 地址字符串(以文本表现形式)。
String ipName = ip.getHostName();//获取此 IP 地址的主机名。
System.out.println(ipAddr+","+ipName);
} catch (UnknownHostException e) {
}

}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值