我试图创建一个简单的Java的HttpServer处理GET请求,但是当我试图让GET参数的请求,我注意到了HttpExchange类不具有该方法。
有谁知道一个简单的方法来读取GET参数(查询字符串)?
这是我的处理程序看起来像:
public class TestHandler{
@Override
public void handle(HttpExchange exc) throws IOxception {
String response = "This is the reponse";
exc.sendResponseHeaders(200, response.length());
// need GET params here
OutputStream os = exc.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
..和主要方法:
public static void main(String[] args) throws Exception{
// create server on port 8000
InetSocketAddress address = new InetSocketAddress(8000);
HttpServer server = new HttpServer.create(address, 0);
// bind handler
server.createContext("/highscore", new TestHandler());
server.setExecutor(null);
server.start();
}
以下内容: httpExchange.getRequestURI().getQuery()
:将在类似这样的格式返回字符串"field1=value1&field2=value2&field3=value3..."
所以你可以简单地自己分析的字符串,这是多么的解析函数可能看起来像:
public Map<String, String> queryToMap(String query) {
Map<String, String> result = new HashMap<>();
for (String param : query.split("&")) {
String[] entry = param.split("=");
if (entry.length > 1) {
result.put(entry[0], entry[1]);
}else{
result.put(entry[0], "");
}
}
return result;
}
这是你如何使用它:
Map<String, String> params = queryToMap(httpExchange.getRequestURI().getQuery());
System.out.println("param A=" + params.get("A"));
通过@ anon01对答案的基础上,这是如何做到这一点在Groovy:
Map<String,String> getQueryParameters( HttpExchange httpExchange )
{
def query = httpExchange.getRequestURI().getQuery()
return query.split( '&' )
.collectEntries {
String[] pair = it.split( '=' )
if (pair.length > 1)
{
return [(pair[0]): pair[1]]
}
else
{
return [(pair[0]): ""]
}
}
}
这是如何使用它:
def queryParameters = getQueryParameters( httpExchange )
def parameterA = queryParameters['A']
这个答案,相反annon01的,正确解码键和值。 它不使用String.split
,但使用扫描字符串indexOf
,这是更快。
public static Map<String, String> parseQueryString(String qs) {
Map<String, String> result = new HashMap<>();
if (qs == null)
return result;
int last = 0, next, l = qs.length();
while (last < l) {
next = qs.indexOf('&', last);
if (next == -1)
next = l;
if (next > last) {
int eqPos = qs.indexOf('=', last);
try {
if (eqPos < 0 || eqPos > next)
result.put(URLDecoder.decode(qs.substring(last, next), "utf-8"), "");
else
result.put(URLDecoder.decode(qs.substring(last, eqPos), "utf-8"), URLDecoder.decode(qs.substring(eqPos + 1, next), "utf-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // will never happen, utf-8 support is mandatory for java
}
}
last = next + 1;
}
return result;
}