javaandroidurluriuribuilder

Java Use URI builder?


I have bellow url :

http://www.example.com/api/Video/GetListMusicRelated/0/0/null/105358/0/0/10/null/null 

This section is Fixed and unchangeable:

http://www.example.com/api/Video/GetListMusicRelated/

I set parameter to this url like bellow :

 http://www.example.com/api/Video/GetListMusicRelated/25/60/jim/105358/20/1/5/null/null 

OR :

http://www.example.com/api/Video/GetListMusicRelated/0/0/null/105358,5875,85547/0/0/10/null/null 

How I can write for this url a url builder ?


Solution

  • If you want to create an UrlBuilder using the builder pattern, it could be done like this:

    public class UrlBuilder {
        private final String root;
        private int myParam1;
        private String myParam2;
    
        public UrlBuilder(final String root) {
            this.root = root;
        }
    
        public UrlBuilder myParam1(int myParam1) {
            this.myParam1 = myParam1;
            return this;
        }
    
        public UrlBuilder myParam2(String myParam2) {
            this.myParam2 = myParam2;
            return this;
        }
    
        public URL build() throws MalformedURLException {
            return new URL(
                String.format("%s/%d/%s", root, myParam1, myParam2)
            );
        }
    }
    

    Then you will be able to create your URL as next

    URL url = new UrlBuilder("http://www.example.com/api/Video/GetListMusicRelated")
        .myParam1(25)
        .myParam2("jim")
        .build();
    

    NB: This only shows the idea, so I used fake parameter's name and incorrect number of parameters, please note that you are supposed to have 6 parameters and set the proper names.