如何从url获取所有变量的HashMap

时间:2013-06-25 10:49:37

标签: java android url

我只想知道如何从URL(Java)中检索URL中的所有变量。

E.g 如果我有以下URL,
http://www.sample.com/json/just_in.asp?variable1=value1&variable2=value2

然后想要检索variable1variable2及其值并将其存储在hashmap其中key=variable name(variable1)

和{ {1}}

4 个答案:

答案 0 :(得分:3)

像这样:

HashMap<String, String> map = new HashMap<String, String>();
try {
    String url = "http://www.sample.com/json/just_in.asp?variable1=value1&variable2=value2";
    List<NameValuePair> parameters = URLEncodedUtils.parse(new URI(url), "UTF-8");
    for (NameValuePair p : parameters) {
        map.put(p.getName(), p.getValue());
    }
} catch (URISyntaxException e) {
    e.printStackTrace();
}

map将包含参数的键/值对。

答案 1 :(得分:2)

从您的网址/字符串中创建一个Uri对象。

String myUrl = "http://www.sample.com/json/just_in.asp?variable1=value1&variable2=value2";

Uri uri = Uri.parse(myUrl);
String variable1 = uri.getQueryParameter("variable1");
String variable2 = uri.getQueryParameter("variable2");

有关该主题的更多信息,请参阅http://developer.android.com/reference/android/net/Uri.html

答案 2 :(得分:1)

使用这个简单的代码

 final String[] params = url.split("&");
        final Map<String, String> map = new HashMap<String, String>();
        try {
            for (final String param : params) {
                final String name = param.split("=")[0];
                final String value = param.split("=")[1];
                map.put(name, value);
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }

答案 3 :(得分:0)

以我为例,

private static final String SYMBOL_EQUAL = "=";
private static final String SYMBOL_COMMA = ",";
private static final String SYMBOL_AND = "&";

   public static HashMap<String, String> getParamList(String encodedUrl) throws IOException {

    final HashMap<String, String> map = new HashMap<String, String>();
    final String url = URLDecoder.decode(encodedUrl, StandardCharsets.UTF_8.name());
    final String[] params = url.split(SYMBOL_AND);

    try {
        for (final String param : params) {
            final String name = param.split(SYMBOL_EQUAL)[0];
            final String value = param.split(SYMBOL_EQUAL)[1];
            map.put(name, value);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage());
    }
    return map;
}