java解析request或url中的参数工具类代码

转载 2019-11-05 21:21 阅读(2545)次

无论我们在做爬虫时还是在做访问日志解析时,都需要java获取request中的参数、java解析URL问号后的参数。有时候我们需要从request中获取参数,或者获取拼接在Url后面的参数,有时候一个一个去拿有点麻烦,一起拿出来放在一个map里面需要用哪个就取哪个,方便省事

代码转载https://www.bbsmax.com/A/GBJrq74Wz0/

上代码:

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class HttpParamUtil {

	/**
	 * 获得url中参数
	 * @param url
	 * @return
	 */
	public static Map<String, Object> getParameter(String url) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			final String charset = "utf-8";
			url = URLDecoder.decode(url, charset);
			if (url.indexOf('?') != -1) {
				final String contents = url.substring(url.indexOf('?') + 1);
				String[] keyValues = contents.split("&");
				for (int i = 0; i < keyValues.length; i++) {
					String key = keyValues[i].substring(0, keyValues[i].indexOf("="));
					String value = keyValues[i].substring(keyValues[i].indexOf("=") + 1);
					map.put(key, value);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 获取request中参数
	 * 
	 * @param request 页面请求
	 */
	public static Map<String, Object> getRequestParameters(HttpServletRequest request) {
		String parameters = "";// 请求参数

		String urlParameter = request.getQueryString();// 网址中的参数
		if (urlParameter != null && !"".equals(urlParameter)) {
			try {
				urlParameter = URLDecoder.decode(urlParameter, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} else {
			urlParameter = "";
		}
		parameters = urlParameter;

		Map<String, Object> map = new HashMap<String, Object>();
		String[] arr = parameters.split("&");
		for (int i = 0; i < arr.length; i++) {
			String key = arr[i].substring(0, arr[i].indexOf("="));
			String value = arr[i].substring(arr[i].indexOf("=") + 1);
			map.put(key, value);
		}
		return map;
	}

	/**
	 * 测试
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		String url = "www.xxxx.com?id=100001&name=zhangsan&age=25";
		Map<String, Object> map = getParameter(url);

		System.out.println(map);
	}
}