不畏浮云遮望眼,只缘身在最高层
分类: 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();
}
}
}
}
}