26

我正在尝试在 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();
}
4

4 回答 4

49

以下:httpExchange.getRequestURI().getQuery()

将以类似于以下格式返回字符串:"field1=value1&field2=value2&field3=value3..."

所以你可以简单地自己解析字符串,这就是解析函数的样子:

public Map<String, String> queryToMap(String query) {
    if(query == null) {
        return null;
    }
    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"));
于 2013-07-04T14:08:58.077 回答
3

与 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;
}
于 2017-01-12T10:32:26.963 回答
1

基于@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']
于 2015-08-31T09:10:06.533 回答
1

偶然发现了这一点,并想我会在这里扔一个Java 8 / Streams实现,同时添加一些额外的位(不是在以前的答案中)。

Extra 1:我添加了一个过滤器以避免处理任何空参数。不应该发生的事情,但它允许更清晰的实现而不是不处理问题(并发送空响应)。这方面的一个例子看起来像?param1=value1&param2=

额外 2:我利用String.split(String regex, int limit)进行第二次拆分操作。这允许诸如?param1=it_has=in-it&other=something传递查询参数。

public static Map<String, String> getParamMap(String query) {
    // query is null if not provided (e.g. localhost/path )
    // query is empty if '?' is supplied (e.g. localhost/path? )
    if (query == null || query.isEmpty()) return Collections.emptyMap();

    return Stream.of(query.split("&"))
            .filter(s -> !s.isEmpty())
            .map(kv -> kv.split("=", 2)) 
            .collect(Collectors.toMap(x -> x[0], x-> x[1]));

}

进口

import java.util.Map;
import java.util.Collections;
import java.util.stream.Stream;
import java.util.stream.Collectors;
于 2020-09-20T07:20:08.203 回答