Java URL Normalize normalize(String url)

Here you can find the source of normalize(String url)

Description

normalize

License

Apache License

Declaration

public static String normalize(String url) 

Method Source Code


//package com.java2s;
/*/*  ww  w  . j  a v  a2 s  .co  m*/
 * Copyright 2006-2008 Appcelerator, Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    public static String normalize(String url) {
        if (null == url) {
            return null;
        }

        if (!url.startsWith("http://")) {
            return normalize("http://" + url);
        }

        URL u;
        try {
            u = new URL(url);
        } catch (MalformedURLException e) {
            return null;
        }

        // pre-compute length of StringBuffer
        int len = u.getProtocol().length() + 1;
        if (u.getAuthority() != null && u.getAuthority().length() > 0) {
            len += 2 + u.getAuthority().length();
        }
        if (u.getPath() != null) {
            len += u.getPath().length();
        }
        ++len; // for the path slash
        if (u.getQuery() != null) {
            len += 1 + u.getQuery().length();
        }
        if (u.getRef() != null) {
            len += 1 + u.getRef().length();
        }

        StringBuilder result = new StringBuilder(len);
        result.append(u.getProtocol());
        result.append(":");
        if (u.getAuthority() != null && u.getAuthority().length() > 0) {
            result.append("//");
            result.append(u.getAuthority());
        }
        String path = u.getPath();
        if (path != null) {
            if (path.endsWith("/")) {
                path = path.substring(0, path.length() - 1);
            }
            result.append(path);
        }
        if (u.getQuery() != null) {
            result.append('?');
            result.append(u.getQuery());
        }
        if (u.getRef() != null) {
            result.append("#");
            result.append(u.getRef());
        }
        return result.toString();
    }
}

Related

  1. normalize(final String taintedURL)
  2. normalize(String absoluteURL)
  3. normalize(String url)
  4. normalize(String url)
  5. normalize(String url_str)
  6. normalize(URL u)
  7. normalize(URL url)