码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-05-12 22:31:19      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

 
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();
		}
	}

}

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

标签:

原文地址:http://blog.csdn.net/qq_28654189/article/details/51353557

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!