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 ?

3
  • might it helps: stackoverflow.com/questions/17736681/… Commented May 25, 2018 at 10:55
  • @MeetTitan Where does the OP mention JSON anywhere? I'm not seeing it. Commented May 25, 2018 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 Commented May 25, 2018 at 14:01

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

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 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.
Thanks again ! Sorry I removed the comment right after posting it when it hit me :)
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());

2 Comments

The only drawback of this approach is that it assumes fixed positions for the two components.
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.
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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.