21

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}

kirtan403
  • 7,293
  • 6
  • 54
  • 97
ChangUZ
  • 5,380
  • 10
  • 46
  • 64

4 Answers4

59

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");
j__m
  • 9,392
  • 1
  • 32
  • 56
  • this is what I want. To use getQueryParameterNames in low api level(<11), we can get method in android open source. – ChangUZ Jul 19 '13 at 01:49
  • (4.2.2 adroid.net.Uri.getQueryParameterNames() method) http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2.2_r1/android/net/Uri.java#Uri.getQueryParameterNames%28%29 – ChangUZ Jul 19 '13 at 01:50
  • This is the right answer. Everyone who said anything about `split()`, myself included, read the question too fast. – Doodad Jul 19 '13 at 01:50
  • 1
    @ChangUZ fyi, the grepcode link does not appear to be working/live. – AJW Jul 22 '20 at 13:59
3

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();
        }

    }

}
Harry.Chen
  • 1,582
  • 11
  • 12
0

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")
nmahnic
  • 91
  • 1
  • 2
0

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() 
};
Sam Ginrich
  • 661
  • 6
  • 7