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();
		}
	}

}

你可能感兴趣的:(URL的通信连接---java URLConnection类)