0

I have a url which looks like this https://test.sample.com/product/<product_Id>/subproduct/<sub_product_id>

I'm trying to get the <product_id> and <sub_product_id> from this in the best clean way possible.

What I've tried is to do a String split, loop through each item and get the items after "product" and "subproduct".

Is this the only way to do this ? Or rather the best possible way ?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
RmK
  • 1,408
  • 15
  • 28
  • might it helps: https://stackoverflow.com/questions/17736681/how-to-parse-or-split-url-address-in-java – sudha May 25 '18 at 10:55
  • @MeetTitan Where does the OP mention JSON anywhere? I'm not seeing it. – Tim Biegeleisen May 25 '18 at 10:56
  • Thanks @sudha but I had already checked that question and it doesn't solve my purpose (because of multiple variables in the path). It's a good approach to isolate the path from the base URl and other query params – RmK May 25 '18 at 14:01

3 Answers3

5

Splitting the url string is one option, but we can try using String#replaceAll for a regex based one liner approach:

String url = "https://test.sample.com/product/<product_Id>/subproduct/<sub_product_id>";
System.out.println(url.replaceAll(".*/product/(.*?)/.*$", "$1"));
System.out.println(url.replaceAll(".*/subproduct/(.*?)$", "$1"));

<product_Id>
<sub_product_id>

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Went ahead with this answer because this insulates the app's code from any changes in the URl structure as long as the IDs are preceded by the key. – RmK May 25 '18 at 13:56
  • 1
    @RmK I don't know what exactly you have in mind by "delimiters," but if you're referring to `/` then no, it doesn't require any special handling. Forward slash is not a metacharacter. – Tim Biegeleisen May 25 '18 at 14:00
  • Thanks again ! Sorry I removed the comment right after posting it when it hit me :) – RmK May 25 '18 at 14:02
1

You can use Uri class in android.net.Uri

  Uri uri = Uri.parse("https://test.sample.com/product/4/subproduct/8");
    List list =  uri.getPathSegments();
    Log.d("productid",list.get(1).toString());
    Log.d("subproductid",list.get(3).toString());
Majva
  • 88
  • 1
  • 5
  • 2
    The only drawback of this approach is that it assumes fixed positions for the two components. – Tim Biegeleisen May 25 '18 at 12:56
  • Thanks Majid. Although I agree with @TimBiegeleisen here because this is going to be used in an app and I wouldn't want do do a new release just because the URL structure got changed. – RmK May 25 '18 at 13:50
0

This works if you know the url will always be formatted the same. String url = "https://test.sample.com/product/asdf/subproduct/qwerty"; String[] urlArray = url.split("/"); // check may be here if the array is at least more than 7 or whatever length you require. String product = urlArray[4]; String subproduct = urlArray[6];