io.github.stylesmile.parse.ParseParameterSunHttpServer Maven / Gradle / Ivy
package io.github.stylesmile.parse;
import com.sun.net.httpserver.HttpExchange;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class ParseParameterSunHttpServer {
/**
* 解析get参数
*/
private void parseGetParameters(HttpExchange exchange, Map parameters) throws UnsupportedEncodingException {
URI requestedUri = exchange.getRequestURI();
String query = requestedUri.getRawQuery();
parseQuery(query, parameters);
}
/**
* 解析post参数
*/
private void parsePostParameters(HttpExchange exchange, Map parameters) throws IOException {
String method = exchange.getRequestMethod();
if ("POST".equalsIgnoreCase(method)
|| "PUT".equalsIgnoreCase(method)
|| "DELETE".equalsIgnoreCase(method)
|| "PATCH".equalsIgnoreCase(method)) {
String ct = exchange.getRequestHeaders().getFirst("Content-Type");
if (ct == null) {
return;
}
if (ct.toLowerCase(Locale.US).startsWith("application/x-www-form-urlencoded") == false) {
return;
}
InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(), "UTF-8");
BufferedReader br = new BufferedReader(isr);
String query = br.readLine();
parseQuery(query, parameters);
}
}
private void parseQuery(String query, Map parameters) throws UnsupportedEncodingException {
if (query != null) {
String pairs[] = query.split("[&]");
for (String pair : pairs) {
String param[] = pair.split("[=]");
String key = null;
String value = null;
if (param.length > 0) {
key = URLDecoder.decode(param[0], "UTF-8");
}
if (param.length > 1) {
value = URLDecoder.decode(param[1], "UTF-8");
} else {
value = "";
}
if (parameters.containsKey(key)) {
Object obj = parameters.get(key);
if (obj instanceof List>) {
List values = (List) obj;
values.add(value);
} else if (obj instanceof String) {
List values = new ArrayList();
values.add((String) obj);
values.add(value);
parameters.put(key, values);
}
} else {
parameters.put(key, value);
}
}
}
}
}