使用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;
        }
    }
}
原文地址:https://www.cnblogs.com/liqiu/p/3394619.html