在JAVA中,Java.net包里面的类是进行网络编程的,其中java.net.URL类和java.net.URLConection类使编程者方便地利用URL在Internet上进行网络通信。

1、创建URL对象
  URL类有多种形式的构造函数:
(1) URL ( String url)
  
//url代表一个绝对地址,URL对象直接指向这个资源,如:
  URL urll=new URL(http://www.cqwu.edu.cn);

(
2) URL ( URL baseURL , String relativeURL)
 
// 其中,baseURL代表绝对地址,relativeURL代表相对地址。如:
  URL urll=new URL(http://www.cqwu.edu.cn);
  URL lib=new URL(urll , "library / library.asp");

(
3) URL ( String protocol , String host , String file)
  
//其中,protocol代表通信协议,host代表主机名,file代表文件名。如:
  new URL ("http" , www.cqwu.edu.cn, "/ test / test.asp");

(
4) URL ( String protocol , String host , int port , String file)
  URL lib 
= new URL ("http" , www.cqwu.edu.cn, 80 , "/ test / test.asp");


2、获取URL对象的属性
  getDefaultPort(): 返回默认的端口号。
  getFile(): 获得URL指定资源的完整文件名。
  getHost(): 返回主机名。
  getPath(): 返回指定资源的文件目录和文件名。
  getPort(): 返回端口号,默认为-1。
  getProtocol(): 返回表示URL中协议的字符串对象。
  getRef(): 返回URL中的HTML文档标记,即#号标记。
  getUserInfo: 返回用户信息。
  toString: 返回完整的URL字符串。


二、Internet寻址
  java.net包可以用32位int形式来操作32位的IP地址(即Internet主机地址)。类InetAddress实际上是可以把Internet地址换算成代表该地址的对象。Java就是靠这个类来显示Internet地址已经相关信息的。
  InetAddress有以下常用方法:
  getAddress(): 返回IP地址的字节形式。
  getAllByName(): 返回指定主机名的IP地址。
  getbyAddress(): 返回指定字节数组的IP地址形式。
  getByName(): 返回指定主机名的IP地址对象。
  getHostAddress(): 返回主机地址的字符串形式。
  getLocalHost(): 返回当前主机名。
  hastCode(): 返回InetAddress对象的哈希码。
  toString: 返回地址转换成的字符串。
  InetAddress类没有提供返回构造函数,所以不能用new()方法来创建它的对象,而只可以调用静态方法getLocalHost()、getByName()、getByAddress()等来生成InetAddress类的实质。

程序代码 程序代码

import java.net.*;
import java.io.*;
public class InetAddDemo //extends Applet
{
 
public void testOperate()
 
{
  
try
  
{
   InetAddress address
=InetAddress.getLocalHost();
   log(
"本机地址字符串:"+address.getHostAddress());
   log(
"本机主机名:"+address.getHostName());
   log(
"本机主机名:"+address.getLocalHost());
   log(
"哈希码:"+address.hashCode());
   
byte b[]=address.getAddress();
   System.out.println(
"字符形式:"+b);
   log(
"地址字符串:"+address.toString());
  }

  
catch(Exception e)
  
{
   
//e.printStackTrace("不能打开这个URL");
  }

 }

 
 
public void log(String strInfo)
 
{
  System.out.println(strInfo);
 }

 
 
public static void main(String args[])
 
{
  InetAddDemo IAdd
=new InetAddDemo();
  IAdd.testOperate();
 }

}




结果: 

本机地址字符串:192.9.200.108
本机主机名:s5
本机主机名:s5
/192.9.200.108
哈希码:
-1073100692
字符形式:[B@f4a24a
地址字符串:s5
/192.9.200.108