0

我只想知道我们如何从 URL 中检索所有变量及其在 android(Java) 中的值。

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

然后想用它的值检索variable1and并将其存储在where和variable2hashmap
key=variable name(variable1)

value=variable value(value1)

4

4 回答 4

3

Like so:

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 will contain key/value pairs of your parameters.

于 2013-06-25T10:55:42.210 回答
2

Create a Uri object out of your URL/string.

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");

See http://developer.android.com/reference/android/net/Uri.html for more information on the topic.

于 2013-06-25T10:55:29.810 回答
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();
        }
于 2013-06-25T11:24:48.017 回答
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;
}
于 2020-10-13T12:12:40.803 回答