Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse or split URL Address in Java?

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}

like image 776
ChangUZ Avatar asked Jul 19 '13 01:07

ChangUZ


People also ask

How do you split a link in Java?

String[] parts = URL. split(":"); String HOST = parts[0]; String PORT = parts[1];

What is URL parsing?

URL Parsing. The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.

What are the methods in the URL class used for parsing the URL?

The URL class provides several methods that let you query URL objects. You can get the protocol, authority, host name, port number, path, query, filename, and reference from a URL using these accessor methods: getProtocol.

How do I convert a string to a URL in Java?

In your Java program, you can use a String containing this text to create a URL object: URL myURL = new URL("http://example.com/"); The URL object created above represents an absolute URL. An absolute URL contains all of the information necessary to reach the resource in question.


2 Answers

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");
like image 179
j__m Avatar answered Sep 29 '22 17:09

j__m


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

    }

}
like image 26
Harry.Chen Avatar answered Sep 29 '22 18:09

Harry.Chen