Android: Create a URL using Uri.Builder().build() with port numbers

9 comments works quite well with normal URLs, but it fails with port number support.

The easiest way that I discovered to make it support port numbers was to make it parse a given URL first then work with it.

Uri.Builder b = Uri.parse("").buildUpon();

b.appendQueryParameter("arg1", String.valueOf(42));

if (username != "") {
b.appendQueryParameter("username", username);

String url =;

And there you have it, a customisable URL with support for port number and queries.


  1. Thanks for this post, i always seem to forget the builder syntax

  2. Nice :) I have problem with create URL which is changeable in one element, e.g:

    Any suggestions?

    1. I would get the path component, split it into an array String[] and replace the changable element index, then set path again.

    2. Any example for it?

    3. No, not really. It's just standard string manipulation.

  3. Thanks for the article,

    im trying to compose an URL that looks like:

    but i get the following strange string:

    The code is:

    Uri.Builder uriBuilder = Uri.parse("").buildUpon()


    uriBuilder.appendQueryParameter("n", "72");
    uriBuilder.appendQueryParameter("email", "");

    Uri uri =;
    URL url = new URL(uri.toString());

    Can't figure out the reason. If i hardcode the string, it works fine.

    Can you help me?

    1. I suspect the last line is where it goes wrong.

      You should be using URI.toURL():


Leave your thoughts ...
If you are having trouble with copy/pasting in comments, you need to sign in or click 'Preview'. For more information about this Firefox bug, see here.

Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog