A.K.
A.K.

Reputation: 3641

How to handle ports in URI.Builder class in Android

When testing my android app in development environment, I want to connect to a server running on port 9000. But when I supply the port to Builder.authority("localhost:9000"), it does not work. On the other hand if I create the same URL by hand like new URL("localhost:9000"), it works fine.

What is the alternative?

Upvotes: 3

Views: 2038

Answers (2)

Madhukar Hebbar
Madhukar Hebbar

Reputation: 3173

Uri.Builder will encode your URL so that ':' is replaced by %3 .

To prevent encoding use the encoded versions of builder functions:

String host = "localhost:9000";
Uri.Builder builder = new Uri.Builder();
builder.encodedAuthority(host);

Upvotes: 6

A.K.
A.K.

Reputation: 3641

Found the solution at http://twigstechtips.blogspot.in/2011/01/android-create-url-using.html. Quoting:

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();

Upvotes: 0

Related Questions