How to Parse or Split Url Address in Java

How to parse or split URL Address in Java?

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

How to split an URL in Java

You can use the following code to get the value for query param code.

String url = "http://localhost.osc-ref.dockercloud.fiducia.de/login?code=11448259-7efe-4c6e-bbce-216bb8578bd5&scope=openid&iss=https%3A%2F%2Fr8840-e40-e.t1.web.fiducia.de%3A443%2Fservices_my-account%2Foauth2%2FXC8840&state=myScope&client_id=fkp";
Uri uri = Uri.parse(url);
String code = uri.getQueryParameter("code");
Log.e("Value for query-param:", code);

how to split string url in java

Just use Integer.parseInt() for the port variable:

 String[] parts = VAC_URL.split(":");
String HOST = parts[1].replaceAll("//","");
int PORT = Integer.parseInt(parts[2]);

or to have it as long use this instead:

long PORT = Long.valueOf(parts[2]).longValue();

URL parse without String split

There are few ways. One of them is using URI#resolve(".") where . represents current directory. So your code can look like:

URI uri = new URI("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println(uri.resolve(".").getPath());

Output: /docs/books/tutorial/


Other way could involve file system and classes which handle it like File or its improved version introduced in Java 7 Path (and its utility class Paths).

These classes should allow you to parse path

/docs/books/tutorial/index.html

and get its parent location /docs/books/tutorial.

URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");

String path = aURL.getPath();
String parent = Paths.get(path).getParent().toString();

System.out.println(parent);// \docs\books\tutorial

(little warning: depending on your OS you may get path separated with \ instead of /)



Related Topics



Leave a reply



Submit