您的位置:首页 > 编程语言 > Java开发

URL的通信连接---java URLConnection类

2016-05-09 15:40 621 查看
 
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();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: