在Java中,處理URL參數通常涉及到解析URL、提取參數以及向URL添加參數
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
public class URLParameters {
public static void main(String[] args) {
String urlString = "https://example.com/test?param1=value1¶m2=value2";
try {
URI uri = new URI(urlString);
String query = uri.getQuery();
Map<String, String> parameters = new HashMap<>();
if (query != null) {
String[] pairs = query.split("&");
for (String pair : pairs) {
int idx = pair.indexOf("=");
parameters.put(pair.substring(0, idx), pair.substring(idx + 1));
}
}
System.out.println("Parameters: " + parameters);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class AddURLParameters {
public static void main(String[] args) {
String baseUrl = "https://example.com/test";
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
String urlWithParameters = addParametersToUrl(baseUrl, parameters);
System.out.println("URL with parameters: " + urlWithParameters);
}
private static String addParametersToUrl(String baseUrl, Map<String, String> parameters) {
StringBuilder urlBuilder = new StringBuilder(baseUrl);
if (parameters != null && !parameters.isEmpty()) {
urlBuilder.append("?");
boolean isFirst = true;
for (Map.Entry<String, String> entry : parameters.entrySet()) {
if (!isFirst) {
urlBuilder.append("&");
} else {
isFirst = false;
}
try {
urlBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
urlBuilder.append("=");
urlBuilder.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
return urlBuilder.toString();
}
}
這些示例展示了如何在Java中解析URL并提取參數,以及如何向URL添加參數。請注意,這些示例僅適用于簡單的URL參數處理。對于更復雜的情況,建議使用專門的庫(如Apache HttpClient或OkHttp)來處理URL和參數。