URL的通信连接---java URLConnection类

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

☆互联网协议(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()     //返回主机名
}



//代码示例

package cn.hncu.url;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import org.junit.Test;

public class URLDemo {
	@Test
	public void urlDemo1() {
		try {
			URL source = new URL("http://www.baidu.com");
			InputStream in = source.openStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in,
					"utf-8"));
			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void urlConnectionDemo(){
		try {
			URL source = new URL("http://www.hncu.net:80");
			URLConnection con = source.openConnection();
			System.out.println( con.getURL() );
			System.out.println( con.getContentLength() );
			System.out.println( con.getContentType() );
			System.out.println( new Date(con.getLastModified()) );
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void inetAddressDemo(){
		try {
			InetAddress ip = InetAddress.getByName("www.sina.com.cn");
			//InetAddress ip = InetAddress.getByName("58.47.143.5");
			System.out.println(ip.getHostAddress());
			System.out.println(ip.getHostName());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void inetAddressDemo2(){
		try {
			URL url = new URL("http://www.hncu.net:80");
			InetAddress ip = InetAddress.getByName(url.getHost());
			System.out.println(ip.getHostAddress());
			System.out.println(ip.getHostName());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值