Chinaunix首页 | 论坛 | 博客
  • 博客访问: 280879
  • 博文数量: 28
  • 博客积分: 11
  • 博客等级: 民兵
  • 技术积分: 895
  • 用 户 组: 普通用户
  • 注册时间: 2012-11-19 19:50
个人简介

不畏浮云遮望眼,只缘身在最高层

文章分类

全部博文(28)

文章存档

2014年(1)

2013年(27)

分类: Java

2013-02-04 12:32:04

public class NetWorkTest{
  public static void main(String [] args) throws Exception
{  
       /*1.InetAddress类使用实例****
         * InetAddress类用来表示互联网地址(IP地址),它封装了IP地址和域名相关的操作方法*/
		//用域名创建InetAddress对象
		InetAddress net1=InetAddress.getByName("");//二级域名
		System.out.println(net1);
		
		//用IP创建InetAddress对象
		InetAddress net2=InetAddress.getByName("219.148.35.60");
		System.out.println(net2);
		
		//获得本机InetAddress对象
		InetAddress net3=InetAddress.getLocalHost();
		System.out.println(net3);
		
		//获得InetAddress对象中存储的域名
		String host=net3.getHostName();
		System.out.println("本机名:"+host); 
		
		//获得InetAddress中存储的IP
		String ip=net3.getHostAddress();
		System.out.println("本机IP为:"+ip);
		/***************************************/
		
		/*2.URL使用实例*/
		//URL是Internet上用来描述信息资源的字符串
		URL ur1=null;
		BufferedReader in=null;
		HttpURLConnection httpurlconnection=null;
		try
		{
			ur1=new URL("http://blog.chinaunix.net/uid/24129645.html");
			httpurlconnection=(HttpURLConnection) ur1.openConnection(); //完成了复杂的联网功能
			//得到请求码(此处只是验证是否成功请求和响应) 返回200,表示联网成功
			int code=httpurlconnection.getResponseCode();
			System.out.println("返回码:"+code);
			
			System.out.println("URL相关属性---------------------------");
			//获得协议
			System.out.println("Protocol:"+ur1.getProtocol());
			//获得主机名
			System.out.println("hostname:"+ur1.getHost());
			//获得端口号
			System.out.println("port:"+ur1.getPort());
			//获得URL的路径
			System.out.println("Path:"+ur1.getPath());
			//获得URL的文件名
			System.out.println("Filename:"+ur1.getFile());
			//把URL的内容转换为字符串
			System.out.println("toString:"+ur1.toString());
			System.out.println("---------------------------");
			in=new BufferedReader(new InputStreamReader(ur1.openStream()));
			//读取信息
			for(String line=null;(line=in.readLine())!=null;)
			{
				System.out.println(line);
			}
		}
		catch(MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if(null!=in)
			{
				try
				{
					in.close();
				}
				catch(IOException e)
				{
					e.printStackTrace();
				}
			}
		}
     }
}

阅读(1332) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~