如何将查询参数作为HashMap

时间:2013-03-04 08:41:09

标签: java jax-rs apache-wink

我希望能够将GET请求传递给我的服务器,如下:

 http://example.com/?a[foo]=1&a[bar]=15&b=3

当我得到查询参数'a'时,它应该被解析为HashMap,如下所示:

{'foo':1, 'bar':15}

编辑:好的,要清楚,这是我想要做的,但是在Java中,而不是PHP:

Pass array with keys via HTTP GET

任何想法如何实现这一目标?

3 个答案:

答案 0 :(得分:1)

没有标准的方法可以做到这一点。

Wink支持javax.ws.rs.core.MultivaluedMap。 因此,如果您发送http://example.com/?a=1&a=15&b=3之类的内容,您将收到:键a值1,15;键b值3。

如果您需要解析?a[1]=1&a[gv]=15&b=3之类的内容,则需要使用javax.ws.rs.core.MultivaluedMap.entrySet()并执行其他解析密钥。

以下是您可以使用的代码示例(未对其进行测试,因此可能包含一些小错误):

String getArrayParameter(String key, String index,  MultivaluedMap<String, String> queryParameters) {
    for (Entry<String, List<String>> entry : queryParameters.entrySet()) {
        String qKey = entry.getKey();
        int a = qKey.indexOf('[');
        if (a < 0) {
            // not an array parameter
            continue;
        }
        int b = qKey.indexOf(']');
        if (b <= a) {
            // not an array parameter
            continue;
        }
        if (qKey.substring(0, a).equals(key)) {
            if (qKey.substring(a + 1, b).equals(index)) {
                return entry.getValue().get(0);
            }
        }
    }
    return null;
}

在您的资源中,您应该这样称呼它:

@GET
public void getResource(@Context UriInfo uriInfo) {
    MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
    getArrayParameter("a", "foo", queryParameters);
}

答案 1 :(得分:1)

您可以将JSON Object作为String传递给URL。但是,如果您需要对其进行编码,则可以使用此链接中给出的方法 http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_restful_encodingUtil.htm 用于编码,然后只需将json对象附加为任何其他字符串

答案 2 :(得分:0)

或者,如果您正在使用HttpServletRequest,那么您可以使用getParameterMap()方法,该方法为您提供所有参数及其值作为map。

e.g。

public void doGet(HttpServletRequest request, HttpServletResponse response)
              throws IOException {

   System.out.println("Parameters : \n"+request.getParameterMap()+"\n End");

}
相关问题