TinyHttpUtil.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package net.morimekta.tiny.server.http;
import java.util.HashMap;
import java.util.Map;
import static java.net.URLDecoder.decode;
import static java.nio.charset.StandardCharsets.UTF_8;
public final class TinyHttpUtil {
/**
* Very simple URL query parser.
*
* @param query The query string.
* @return Map of query argument to value.
*/
public static Map<String, String> parseQuery(String query) {
if (query == null) {
return Map.of();
}
if (query.isEmpty()) {
return Map.of();
}
var queryMap = new HashMap<String, String>();
for (String part : query.split("&")) {
if (part.isEmpty()) {
continue;
}
String[] kv = part.split("=", 2);
if (kv[0].isEmpty()) {
// Ignore argument?
continue;
}
if (kv.length == 2) {
queryMap.put(decode(kv[0], UTF_8), decode(kv[1], UTF_8));
} else {
queryMap.put(decode(kv[0], UTF_8), "");
}
}
return Map.copyOf(queryMap);
}
// ------ PRIVATE ------
private TinyHttpUtil() {}
}