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

9 comments

Uri.Builder.build() 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("http://www.yoursite.com:12345").buildUpon();

b.path("/path/to/something/");
b.appendQueryParameter("arg1", String.valueOf(42));

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

String url = b.build().toString();

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

9 comments:

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

    ReplyDelete
  2. Nice :) I have problem with create URL which is changeable in one element, e.g: www.example.com/content/_element_changeable_/img/lib/etc..

    Any suggestions?

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

      Delete
    2. Any example for it?

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

      Delete
  3. Thanks for the article,

    im trying to compose an URL that looks like:

    http://subdomain.page.com:5555/validation.php?n=72&email=a@a.com

    but i get the following strange string:

    http://subdomain.page.com%3A5555/validation.php?n=72&email=a@a.com

    The code is:

    Uri.Builder uriBuilder = Uri.parse("subdomain.page.com:5555").buildUpon()
    .scheme("http");

    uriBuilder.path("/validation.php");

    uriBuilder.appendQueryParameter("n", "72");
    uriBuilder.appendQueryParameter("email", "a@a.com");


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

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

    Can you help me?

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

      You should be using URI.toURL(): http://developer.android.com/reference/java/net/URI.html#toURL%28%29

      Delete

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