网络 java.net

来源:互联网 发布:nginx 变量拼接 编辑:程序博客网 时间:2024/06/05 05:27

1.InetAddress类

       该类用来封装IP地址以及对应的域名

1.1 工厂方法

InetAddress没有可见的构造方法,创建InetAddress对象必须使用可用的工厂方法中的一个。常用的工厂方法如下:

InetAddress  getLocalHost()

getByName()

getAllByName()


eg:

public static void main(String args[]) throws UnknowHostException{

InetAddress address = InetAddress.getLocalHost();


address = InetAddress.getByName("www.baidu.com");


address = InetAddress.getAllByName("www.google.com");

}



1.2 实例方法

String  getHostAdress()

String  getHostName()

byte[]   getAddress()

String toString()      返回主机名和ip地址

boolean equals(Object other)





2.TCP/IP 客户socket

java中有两种类型的socket,一个服务器ServerSocket,用于监听客户的连接,一个用于客户端Socket。


构造方法:

Socket(String hostName,int port)   创建一个连接本地主机到指定名字和端口的主机的socket

Socket(InetAddress ipAddress,int port)     创建一个已经存在的InetAddress对象和一个端口的socket


查看地址和端口信息:

InetAddress getInetAddress()

int getPort()

int getLocalPort()


获得访问与socket关联的输入输出流的权力:

InputStream getInputStream()

OutPutStream getOutputStream()



3.URL  统一资源定位符


eg:    http://www.osborne.com/                         http://www.osborne.com:80/index.htm


URL分为4个组分的基础

1.使用的协议,使用“:”与其他部分分开,常见的协议有http,ftp,file等

2.主机名或者ip地址  使用左边“//”和右边“/”或者“:”来定界

3.端口  可选,由左边的“:”和右边的“/”定界    默认为http的80端口

4.实际的文件路径   index.htm或者index.html



构造函数:

URL(String urlSpecifier)

URL(String protocolName,String hostName,int port,String path)  和URL的四部分一致

URL(URL urlObj,String urlDSpecifer)



eg:

public static void main(String args[]){

URL url = new URL("  http://www.osborne.com:80/index.htm ");

sysout(url.getProtocol());

sysout( url.getport() );

sysout( url.getHost() );

sysout( url.getFile() );

sysout( url.toExternalForm() );

}


结果:

http

80     //若没有显式的设置,则该值为-1;

www.osborne.com

/index.htm

 http://www.osborne.com:80/index.htm 



4.URLConnection 

该类是访问远程资源的一个通用类

我们使用openConnection()方法创建一个URLConnection对象,然后可以检测文档的属性和内容


eg:

public static voird main(String args[]){

int c;

URL url = new URL(" http://www.osborne.com:80/index.htm ");


URLConnection con = url.openConnection();


//获取日期

long date = con.getDate();


sysout ( con.getContentType() );


//get content length

int len = con.getContentLength();


//get Content


if( len != 0){

InputStream in = con.getInputStream();

int i = 0;

while( ( c = in.read() ) != -1 ){

sysout( (char)c );

in.close();

}

}

}



type//文件类型

content//显示网页的html信息