2024年6月11日发(作者:)
HTTPserver从HttpExchange解析参数
You now in Java 6 has some APIs to create lightweight HTTP server. Well, today,
I had to created a lightweight HTTP server embedded in an application, but when I
try to get the parameters for a request I noticed the HttpExchange class doesn’t
have a method for that.
After some researches on Google, I come across a solution.
What I did was to create a Filter class which will deal with the parameters
parse:
public class ParameterFilter extends Filter {
@Override
public String description() {
return "Parses the requested URI for parameters";
}
@Override
public void doFilter(HttpExchange exchange, Chain chain)
throws IOException {
parseGetParameters(exchange);
parsePostParameters(exchange);
er(exchange);
}
private void parseGetParameters(HttpExchange exchange)
throws UnsupportedEncodingException {
Map
URI requestedUri = uestURI();
String query = Query();
parseQuery(query, parameters);
ribute("parameters", parameters);
}
private void parsePostParameters(HttpExchange exchange)
throws IOException {
if ("post".equalsIgnoreCase(uestMethod())) {
@SuppressWarnings("unchecked")
Map
(Map
InputStreamReader isr =
new InputStreamReader(uestBody(),"utf-8");
BufferedReader br = new BufferedReader(isr);
String query = ne();
parseQuery(query, parameters);
}
}
@SuppressWarnings("unchecked")
private void parseQuery(String query, Map
throws UnsupportedEncodingException {
if (query != null) {
String pairs[] = ("[&]");
for (String pair : pairs) {
String param[] = ("[=]");
String key = null;
String value = null;
if ( > 0) {
key = (param[0],
perty("ng"));
}
if ( > 1) {
value = (param[1],
perty("ng"));
}
if (nsKey(key)) {
Object obj = (key);
if(obj instanceof List>) {
List
(value);
} else if(obj instanceof String) {
List
((String)obj);
(value);
(key, values);
}
} else {
(key, value);
}
}
}
}
}
After that you can add this filter to your HttpServer context:
HttpServer server = (new InetSocketAddress(80), 0);
HttpContext context = Context("/myapp", new myHttpHandler());
ters().add(new ParameterFilter());
();
Then you can do something like below in your HttpHandler to get the
parameters:
public class MyHttpHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
Map
(Map
//now you can use the params
}
}
Well, that’s all! I hope you enjoy the tip!
发布评论