获得URl信息

 

 
public class GetUrlInfo
{
    public static void printfInfo(URL url)throws Exception
    {
        //基本信息
        System.out.println("文件        "+url.getFile());
        System.out.println("Protocol        "+url.getProtocol());//获取URL的协议名称
        System.out.println("host        "+url.getHost());
        System.out.println("端口        "+url.getPort());//获取URl的端口号
        System.out.println("路径        "+url.getPath());//获取URL的路径部分
 
 
        URLConnection c=url.openConnection();
        c.connect();
        System.out.println("Contend type        "+c.getContentType());
        System.out.println("Contend Encoding        "+c.getContentEncoding());
        System.out.println("Contend Length        "+c.getContentLength());
        System.out.println("Date        "+new Date(c.getDate()));
        System.out.println("Date        "+new Date(c.getLastModified()));
        System.out.println("Expriration        "+new Date(c.getExpiration()));
 
        if(c instanceof HttpURLConnection)
        {
            HttpURLConnection h=(HttpURLConnection) c;
            System.out.println(" reust Method        "+h.getRequestMethod());
            System.out.println(" Resonse Message        "+h.getResponseMessage());
            System.out.println(" Resonse Code         "+h.getResponseCode());
        }
 
 
 
    }
 
    public static void vist(URL url)throws Exception//抓取某网站的内容
    {
 
        File file=new File("C:/hhh2.txt");
        String tempString;
        StringBuffer sb=new StringBuffer();
         //InputStream in=new InputStreamReader(url.openStream())
        BufferedReader in=new BufferedReader(new InputStreamReader(url.openStream()));
        BufferedWriter out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
        while((tempString=in.readLine())!=null)
        {
            //out.write(tempString);
            //sb.append(tempString);
            System.out.println(tempString);
        }
        in.close();
        out.close();
        System.out.println(sb.toString());
    }
    public static void main(String []args)
    {
        String urlString="https://www.zhihu.com/question/48629658";
        try
        {
            URL url=new URL(urlString);
            System.out.println(url.getUserInfo());
            vist(url);
            //printfInfo(url);
        } catch (Exception e)
        {
            // TODO: handle exception
        }
 
    }
}

 

posted @ 2016-07-27 11:07  -梦里不知身是客  阅读(128)  评论(0编辑  收藏  举报