4

I need to get host from this url

android-app://com.google.android.googlequicksearchbox?Pub_id={siteID} 

java.net.URL and java.net.URI can't handle it.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
Dennis Gloss
  • 2,307
  • 4
  • 21
  • 27
  • If there is no protocol handler installed for `android-app:` then one would receive an exception with "unknown protocol". Also `{}` might be problemation: `"...?Pub_id=" + URLEncoder.encode("{siteID}", "UTF-8"):` Though I suspect you need to fill in `{siteId}`. – Joop Eggen Jan 17 '19 at 13:22

3 Answers3

8

The problem is in { and } characters which are not valid for URI. Looks like a placeholder that wasn't resolved correctly when creating a URI.

You can use String.replaceAll() to get rid of these two characters:

String value = "android-app://com.google.android.googlequicksearchbox?Pub_id={siteID}";
URI uri = URI.create(value.replaceAll("[{}]", ""));
System.out.println(uri.getHost()); // com.google.android.googlequicksearchbox
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
1

You see, eventually I need path, scheme and query.
I've just found super fast library for parsing such URLs. https://github.com/anthonynsimon/jurl
It's also very flexible.

Dennis Gloss
  • 2,307
  • 4
  • 21
  • 27
0

You can try the following code

String url = "android-app://com.google.android.googlequicksearchbox?Pub_id={siteID}";
        url = url.replace("{", "").replace("}","");
        URI u;
        try {
            u = new URI(url);
            System.out.println(u.getHost());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
UVM
  • 9,776
  • 6
  • 41
  • 66