21
votes

If I have url address.

https://graph.facebook.com/me/home?limit=25&since=1374196005

Can I get(or split) parameters (avoiding hard coding)?

Like this

https /// graph.facebook.com /// me/home /// {limit=25, sincse=1374196005}

4
do you want to parse parameters (limit,since) and their value in a map?kvh
You can use .split() to split them based on various delimiters like / or ? . Is that what you want?Shobhit Puri
@kevinhoo Map is good for me. or getParmKeys(), and getParmVal(parmKey)?ChangUZ
you may be you are looking for this:stackoverflow.com/questions/1667278/…kvh
@kevinhoo Yes, Before asking, I could not find good answer.ChangUZ

4 Answers

57
votes

Use Android's Uri class. http://developer.android.com/reference/android/net/Uri.html

Uri uri = Uri.parse("https://graph.facebook.com/me/home?limit=25&since=1374196005");
String protocol = uri.getScheme();
String server = uri.getAuthority();
String path = uri.getPath();
Set<String> args = uri.getQueryParameterNames();
String limit = uri.getQueryParameter("limit");
3
votes

For pure Java , I think this code should work:

import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class UrlTest {
    public static void main(String[] args) {
        try {
            String s = "https://graph.facebook.com/me/home?limit=25&since=1374196005";
            URL url = new URL(s);
            String query = url.getQuery();
            Map<String, String> data = new HashMap<String, String>();
            for (String q : query.split("&")) {
                String[] qa = q.split("=");
                String name = URLDecoder.decode(qa[0]);
                String value = "";
                if (qa.length == 2) {
                    value = URLDecoder.decode(qa[1]);
                }

                data.put(name, value);
            }
            System.out.println(data);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
0
votes

In kotlin

https://graph.facebook.com/me/home?limit=25&since=1374196005

import java.net.URI
import android.net.Uri
val uri = URI(viewEvent.qr)
val guid = Uri.parse(uri.fragment).getQueryParameter("c")
0
votes

Built-in java.net.URL should serve.

URL url = new URL("https://graph.facebook.com/me/home?limit=25&since=1374196005");

String[] parts = {
   url.getProtocol(), 
   url.getUserInfo(), 
   url.getHost(), 
   url.getPort(), 
   url.getPath(),
   url.getQuery(), 
   url.getRef() 
};