zoukankan      html  css  js  c++  java
  • 使用JAVA的URL类处理url事例

    import java.net.*;
    import java.io.*;
    
    public class ParseURL {
    
        public static void main(String[] args)
    
        throws Exception {
    
            URL aURL = new URL("http://java.sun.com:80/docs/books/tutorial" + "/index.html?name=networking#DOWNLOADING");
    
            System.out.println("protocol = " + aURL.getProtocol());
            System.out.println("authority = " + aURL.getAuthority());
            System.out.println("host = " + aURL.getHost());
            System.out.println("port = " + aURL.getPort());
            System.out.println("path = " + aURL.getPath());
            System.out.println("query = " + aURL.getQuery());
            System.out.println("filename = " + aURL.getFile());
            System.out.println("ref = " + aURL.getRef());
        }
    
    }

    输出

    ut:ut:protocol = http
    ut:ut:authority = localhost:8080
    ut:ut:host = localhost
    ut:ut:port = 8080
    ut:ut:path = /UT2.0/login.action
    ut:ut:query = null
    ut:ut:filename = /UT2.0/login.action
    ut:ut:ref = null

    判断URL是否合法

    文件:Test.java

    import java.net.HttpURLConnection;
    import java.net.URL;
    public class Test {
        public static void main(String[] args) {
           System.out.println(exists("http://www.baidu.com"));
           System.out.println(exists("http://www.baidu.com/XXXXX.html"));
        }
        static boolean exists(String URLName) {
           try {
               //设置此类是否应该自动执行 HTTP 重定向(响应代码为 3xx 的请求)。
               HttpURLConnection.setFollowRedirects(false);
               //到 URL 所引用的远程对象的连接
               HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
               /* 设置 URL 请求的方法, GET POST HEAD OPTIONS PUT DELETE TRACE 以上方法之一是合法的,具体取决于协议的限制。*/
               con.setRequestMethod("HEAD");
               //从 HTTP 响应消息获取状态码
               return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
           } catch (Exception e) {
               e.printStackTrace();
               return false;
            }
        }
    }
  • 相关阅读:
    springMVC 是单例还是的多例的?
    js如何获取数字占的位数~
    java 为什么wait(),notify(),notifyAll()必须在同步方法/代码块中调用?
    数据挖掘基本概念讲解
    js如何判断小数点后有几位
    volotile关键字的内存可见性及重排序
    上传文件multipart form-data boundary 说明
    vi 调到第一行和最后一行
    linux监控平台搭建-磁盘
    Guava Cache 参数配置说明
  • 原文地址:https://www.cnblogs.com/liqiu/p/3394619.html
Copyright © 2011-2022 走看看