判断URL中是否有某一特定参数:
public static boolean hasParameter(String urlString, String parameterName) {try {URL url = new URL(urlString);String query = url.getQuery();if (query != null) {String[] params = query.split("&");for (String param : params) {String[] keyValue = param.split("=");if (keyValue.length > 0) {String key = URLDecoder.decode(keyValue[0], "UTF-8");if (key.equals(parameterName)) {return true;}}}}} catch (Exception e) {e.printStackTrace();}return false;}
获取特定参数的值:
public static String getParameterValue(String urlString, String parameterName) {try {URL url = new URL(urlString);String query = url.getQuery();if (query != null) {String[] params = query.split("&");for (String param : params) {String[] keyValue = param.split("=");if (keyValue.length > 1) {String key = URLDecoder.decode(keyValue[0], "UTF-8");String value = URLDecoder.decode(keyValue[1], "UTF-8");if (key.equals(parameterName)) {return value;}}}}} catch (Exception e) {e.printStackTrace();}return null;}
修改特定参数的值:
public static String modifyParameterValue(String urlString, String parameterName, String newValue) {try {URL url = new URL(urlString);String query = url.getQuery();if (query != null) {String[] params = query.split("&");StringBuilder modifiedQuery = new StringBuilder();for (String param : params) {String[] keyValue = param.split("=");if (keyValue.length > 0) {String key = keyValue[0];if (key.equals(parameterName)) {String encodedValue = URLEncoder.encode(newValue, "UTF-8");modifiedQuery.append(key).append("=").append(encodedValue).append("&");} else {modifiedQuery.append(param).append("&");}}}if (modifiedQuery.length() > 0) {modifiedQuery.deleteCharAt(modifiedQuery.length() - 1); // Remove the trailing '&'String modifiedUrlString = urlString.replace(query, modifiedQuery.toString());return modifiedUrlString;}}} catch (Exception e) {e.printStackTrace();}return urlString;}