import java.net.URL; import java.net.URLConnection; import java.net.ConnectException; import java.io.IOException; import java.util.Date; import java.net.HttpURLConnection; public class GetURLInfo{ public static void printInfo(URL url){ System.out.println("==================URL info=================="); //URL基本信息 System.out.println("File ["+url.getFile()+"]"); System.out.println("Protocol ["+url.getProtocol()+"]"); System.out.println("Authority ["+url.getAuthority()+"]"); System.out.println("DefaultPort ["+url.getDefaultPort()+"]"); System.out.println("Host ["+url.getHost()+"]"); System.out.println("Path ["+url.getPath()+"]"); System.out.println("Port ["+url.getPort()+"]"); System.out.println("Query ["+url.getQuery()+"]"); System.out.println("Ref ["+url.getRef()+"]"); System.out.println("UserInfo ["+url.getUserInfo()+"]"); URLConnection c = null; try{ c = url.openConnection(); System.out.println("==================URLConnection info=================="); //显示信息 System.out.println("ContentType [" + c.getContentType() + "]"); System.out.println("ContentEncoding [" + c.getContentEncoding() + "]"); System.out.println("Content [" + c.getContent() + "]"); System.out.println("ContentLength [" + c.getContentLength() + "]"); System.out.println("Date [" + new Date(c.getDate()) + "]"); System.out.println("LastModified [" + new Date(c.getExpiration()) + "]"); System.out.println("Expiration [" + new Date(c.getLastModified()) + "]"); if(c instanceof HttpURLConnection){ System.out.println("==================HttpURLConnection info=================="); HttpURLConnection httpURL = (HttpURLConnection)c; System.out.println("RequestMethod [" + httpURL.getRequestMethod() + "]"); System.out.println("ResponseMessage [" + httpURL.getResponseMessage() + "]"); System.out.println("ResponseCode [" + httpURL.getResponseCode() + "]"); } }catch(IOException e){ e.printStackTrace(); } } public static void main(String[] args){ try{ String urlStr = "http://www.sina.com.cn:80/index.html"; URL url = new URL(urlStr); printInfo(url); }catch(Exception e){ System.err.println(e); } } }
运行结果:
G:\maul keyboard\network programming>javac GetURLInfo.java
G:\maul keyboard\network programming>java GetURLInfo
==================URL info==================
File [/index.html]
Protocol [http]
Authority [www.sina.com.cn:80]
DefaultPort [80]
Host [www.sina.com.cn]
Path [/index.html]
Port [80]
Query [null]
Ref [null]
UserInfo [null]
==================URLConnection info==================
ContentType [text/html]
ContentEncoding [null]
Content [[email protected]b9ce]
ContentLength [21826]
Date [Sat Sep 08 18:29:00 GMT+08:00 2018]
LastModified [Sat Sep 08 18:28:54 GMT+08:00 2018]
Expiration [Wed Apr 27 10:00:04 GMT+08:00 2005]
==================HttpURLConnection info==================
RequestMethod [GET]
ResponseMessage [OK]
ResponseCode [200]
G:\maul keyboard\network programming>
原文地址:https://www.cnblogs.com/celine/p/9610005.html