Java下的URL生成类

  该类用于生成一个可用的URL,方便URL的生成和管理。

/**
 * 构造的URL
 * @author Alvin
 */
final public class UrlBuilder {

	// 协议名称
	private String scheme;

	// 服务器名称
	private String serverName;

	// 端口号
	private int serverPort;

	// 上下文名称
	private String[] paths;

	// 参数集合
	private Map<String, Object> parameters;

	// 地址缓冲
	private String urlBuffer = null;

	// 路径缓冲
	private String pathBuffer = null;
	
	// 参数缓冲
	private String parametersBuffer = null;
	
	/**
	 * 构造器
	 */
	public UrlBuilder(String scheme, String serverName, int serverPort, String[] paths) {
		if (paths != null) {
			for (int i = 0; i < paths.length; i++) {
				paths[i] = trimSeparator(paths[i]);
			}
		}
		this.scheme = scheme;
		this.serverName = serverName;
		this.serverPort = serverPort;
		this.paths = paths;
	}

	/**
	 * 构造器
	 */
	public UrlBuilder(String serverName, int serverPort, String[] paths) {
		this("http", serverName, serverPort, paths);
	}

	/**
	 * 构造器
	 */
	public UrlBuilder(String serverName, int serverPort) {
		this(serverName, serverPort, null);
	}

	/**
	 * 构造器
	 */
	public UrlBuilder(String serverName) {
		this(serverName, 80, null);
	}

	/**
	 * 去除字符串前后的 /
	 */
	private static String trimSeparator(String path) {
		boolean b1 = path.startsWith("/"), b2 = path.endsWith("/");
		if (b1 && b2) {
			path = path.substring(1, path.length() - 1);
		} else if (b1) {
			path = path.substring(1);
		} else if (b2) {
			path = path.substring(0, path.length() - 1);
		}
		return path;
	}

	/**
	 * 添加一个目录
	 */
	public void addPath(String path) {
		path = trimSeparator(path);
		if (path.isEmpty() == false) {
			pathBuffer = null;
			urlBuffer = null;
			if (paths == null) {
				paths = new String[] { path };
			} else {
				paths = Arrays.copyOf(paths, paths.length + 1);
				paths[paths.length - 1] = path;
			}
		}
	}

	/**
	 * 添加若干目录
	 */
	public void addPath(String...paths) {
		List<String> pathList = new ArrayList<>();
		for (String path : paths) {
			path = trimSeparator(path);
			if (path.isEmpty() == false) {
				pathList.add(path);
			}
		}
		if (pathList.isEmpty() == false) {
			pathBuffer = null;
			urlBuffer = null;
			if (this.paths == null) {
				this.paths = pathList.toArray(new String[pathList.size()]);
			} else {
				int len = this.paths.length;
				this.paths = Arrays.copyOf(this.paths, len + pathList.size());
				for (int i = 0; i < pathList.size(); i++) {
					this.paths[len + i] = pathList.get(i);
				}
			}
		}
	}

	/**
	 * 删除目录
	 */
	public String removePath(int index) {
		String value = paths[index];
		String[] newArray = new String[paths.length - 1];
		System.arraycopy(paths, 0, newArray, 0, index);
		System.arraycopy(paths, index + 1, newArray, index, newArray.length - index);
		paths = newArray;
		urlBuffer = null;
		pathBuffer = null;
		return value;
	}

	/**
	 * 转为字符串
	 */
	public String toString(String encoding) {
		if (urlBuffer == null) {
			StringBuilder b = new StringBuilder(scheme);
			b.append("://");
			b.append(serverName);
			b.append(serverPort == 80 ? "" : ":" + serverPort);
			String path = getPath();
			if (path.isEmpty() == false) {
				b.append("/" + path);
			}
			String paramString = getParamString(encoding);
			if (paramString.isEmpty() == false) {
				b.append("?");
				b.append(paramString);
			}
			urlBuffer = b.toString();
		}
		return urlBuffer;
	}

	@Override
	public String toString() {
		return toString("UTF-8");
	}

	/**
	 * 添加一个参数
	 */
	public void addParameter(String name, Object value) {
		if (parameters == null) {
			parameters = new LinkedHashMap<>();
		}
		parametersBuffer = null;
		parameters.put(name, value);
	}

	/**
	 * 删除一个参数
	 */
	public Object removeParameter(String name) {
		if (parameters == null) {
			return null;
		}
		parametersBuffer = null;
		return parameters.remove(name);
	}

	/**
	 * 获取一个参数
	 */
	public Object getParameter(String name) {
		if (parameters == null) {
			return null;
		}
		return parameters.get(name);
	}

	public void setScheme(String scheme) {
		this.scheme = scheme;
		urlBuffer = null;
	}
	public String getScheme() {
		return scheme;
	}
	public void setServerName(String serverName) {
		this.serverName = serverName;
		urlBuffer = null;
	}
	public String getServerName() {
		return serverName;
	}
	public void setServerPort(int serverPort) {
		this.serverPort = serverPort;
		urlBuffer = null;
	}
	public int getServerPort() {
		return serverPort;
	}
	public String getPath(int index) {
		return paths[index];
	}
	public String getPath() {
		if (paths == null) {
			return "";
		}
		if (pathBuffer == null) {
			StringBuilder s = new StringBuilder();
			for (String path : paths) {
				if (s.length() > 0) {
					s.append("/");
				}
				s.append(path);
			}
			pathBuffer = s.toString();
		}
		return pathBuffer;
	}
	public String getParamString(String encoding) {
		if (parametersBuffer == null) {
			parametersBuffer = makeParameters(parameters, encoding);
		}
		return parametersBuffer;
	}
	public String getParamString() {
		return getParamString("UTF-8");
	}

	/**
	 * 解析URL
	 */
	public static UrlBuilder parse(String url, String urlEncoding) {
		String schema, serverName, path = null, queryString = null;
		int pos, pos2, port;

		pos = url.indexOf("://");
		if (pos < 0) {
			schema = "http";
			pos = 0;
		} else {
			schema = url.substring(0, pos).trim();
			if (schema.isEmpty()) {
				throw new IllegalArgumentException(url);
			}
			pos += 3;
		}
		pos2 = url.indexOf("/", pos);
		if (pos2 < 0) {
			serverName = url.substring(pos);
		} else {
			serverName = url.substring(pos, pos2).trim();
		}
		pos = pos2 + 1;
		
		if (serverName.isEmpty()) {
			throw new IllegalArgumentException(url);
		}
		pos2 = serverName.lastIndexOf(":");
		if (pos2 < 0) {
			port = 80;
		} else {
			port = Integer.parseInt(serverName.substring(pos2 + 1));
			serverName = serverName.substring(0, pos2);
		}
		if (pos > 0) {
			pos2 = url.indexOf("?", pos);
			if (pos2 < 0) {
				path = url.substring(pos);
			} else {
				path = url.substring(pos, pos2);
				pos = pos2 + 1;
				queryString = url.substring(pos);
			}
		}
		UrlBuilder builder = new UrlBuilder(schema, serverName, port, path == null ? null : path.split("/"));
		if (queryString != null) {
			String[] qs = queryString.split("&");
			if (qs != null) {
				builder.parameters = new LinkedHashMap<>();
				for (String q : qs) {
					String[] nv = q.split("=", 2);
					if (nv != null) {
						try {
							builder.parameters.put(nv[0], nv.length > 1 ? URLDecoder.decode(nv[1], urlEncoding) : "");
						} catch (UnsupportedEncodingException e) {
							throw new IllegalArgumentException(url);
						}
					}
				}
			}
		}
		return builder;
	}
	
	/**
	 * 解析URL
	 */
	public static UrlBuilder parse(String url) {
		return parse(url, "UTF-8");
	}
	
	/**
	 * 产生参数字符串
	 */
	public static String makeParameters(Map<String, Object> parameters, String encoding) {
		if (parameters == null || parameters.isEmpty()) {
			return "";
		}
		StringBuilder s = new StringBuilder();
		for (Entry<String, Object> e : parameters.entrySet()) {
			if (s.length() > 0) {
				s.append("&");
			}
			s.append(e.getKey());
			s.append("=");
			try {
				s.append(e.getValue() == null ? "" : URLEncoder.encode(String.valueOf(e.getValue()), encoding));
			} catch (UnsupportedEncodingException e1) {
				throw new IllegalArgumentException(encoding);
			}
		}
		return s.toString();
	}
	
	/**
	 * 产生参数字符串
	 */
	public static String makeParameters(Map<String, Object> parameters) {
		return makeParameters(parameters, "UTF-8");
	}
	
	/**
	 * 连接两个地址
	 */
	public static String combinUrl(String url1, String url2) {
		boolean b1 = url1.endsWith("/"), b2 = url2.startsWith("/");
		if (b1 && b2) {
			return url1 + url2.substring(1);
		}
		if (b1 || b2) {
			return url1 + url2;
		}
		return url1 + "/" + url2;		
	}
}

  测试代码如下:

@Test
public void test() {
	UrlBuilder builder = new UrlBuilder("localhost", 8080);
	builder.addPath("xxx");
	System.out.println(builder.toString());
	
	builder.addPath("aaa", "bbb");
	System.out.println(builder.toString());
	
	builder.removePath(1);
	System.out.println(builder.toString());
	
	builder.addParameter("id", 100);
	System.out.println(builder.toString());
	
	builder.addParameter("name", "小李");
	System.out.println(builder.toString());
	
	builder.removeParameter("id");
	System.out.println(builder.toString());
	
	builder = UrlBuilder.parse("http://www.baidu.com:80/test/a.jsp?id=1");
	System.out.println(builder);
}

Java下的URL生成类,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。