标签:
抽象类 URLConnection 是所有类的超类,它代表应用程序和 URL 之间的通信链接。此类的实例可用于读取和写入此 URL 引用的资源。通常,创建一个到 URL 的连接需要几个步骤:
openConnection()
对影响到远程资源连接的参数进行操作。
connect()
与资源交互;查询头字段和内容。
import java.net.*; import java.io.*; import java.util.Date; public class URLConnectionDemo { public static void main(String[] args) throws Exception{ // URLConnectionDemo urlconnectiondemo = new URLConnectionDemo(); int c; URL hp=new URL("http://www.hao123.com/"); URLConnection hpCon=hp.openConnection(); System.out.println("Date: "+new Date(hpCon.getDate())); System.out.println("Content-Type: "+hpCon.getContentType()); System.out.println("Expires: "+hpCon.getExpiration()); System.out.println("Last-Modified: "+ new Date(hpCon.getLastModified())); int len=hpCon.getContentLength(); System.out.println("Content-Length: "+len); if (len>0) { System.out.println("=== content ==="); InputStream input=hpCon.getInputStream(); int i=len; while ((c=input.read())!=-1 && (--i>0)) { System.out.print((char)c); } } else System.out.println("No Content Available!"); } }
运行结果:
Date: Mon Aug 27 11:07:02 CST 2007 Content-Type: text/html Expires: 1188443222000 Last-Modified: Fri Aug 24 12:29:00 CST 2007 Content-Length: 44966 === content === <html><head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> ……
标签:
原文地址:http://www.cnblogs.com/hwaggLee/p/4940018.html