Ciff
Ciff

Reputation: 588

Create a url which contains '&'

When i call a webservice i pass certain values in that url.

Example:

https://website.com/webserviceName/login?userName=user&password=pass

but what if the values have "&" in them.When i form such an url which contains an item with '&' the url breaks at that point returns a fault code. How do i over come this problem.

Example:

https://website.com/webserviceName/login?userName=user&user&password=pass

the problem with this url is that it breaks at the first '&'

The problem can be solved by using URLEncoder.encode(urlXml) http://www.tutorialspoint.com/html/html_url_encoding.htm

Thanx everyone

Upvotes: 2

Views: 122

Answers (3)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

You must encode the ampersand & with %26. So your URL will become

https://website.com/webserviceName/login?userName=user%26user&password=pass

If your username is not fixed and you want to use URLEncoder.encode as @SudhanshuUmalkar suggested, you should encode the arguments only

String url = "https://website.com/webserviceName/login?userName="
             + URLEncoder.encode(userName, "UTF-8") + "&password="
             + URLEncoder.encode(password, "UTF-8");

Since encode(String) is deprecated, you should use encode(String, "UTF-8") or whatever your character set is.

Upvotes: 3

Shade
Shade

Reputation: 10001

I have code working with literal ampersands in it. Your code could break because you don't provide a valid key-value parameter pair:

https://website.com/webserviceName/login?userName=user&user&password=pass
                                                       ^ this shouldn't be like this

The code below works in production:

public static final String DATA_URL = "http://www.example.com/sub/folder/api.php?time=%s&lang=%s&action=test";
String.format (API.DATA_URL, "" + now, language)

Upvotes: 0

Sudhanshu Umalkar
Sudhanshu Umalkar

Reputation: 4202

Use URLEncoder.encode() method.

url = "https://website.com/webserviceName/login?" + URLEncoder.encode("userName=user&user&password=pass", "UTF-8");

Upvotes: 2

Related Questions