简体   繁体   中英

How to replace “ ” with %20 in android

I am doing a service call functionality in android. In the following URL(String) I need to replace " " (space) with %20

http://dli.ircms.in/complaint.php?complaintno=sarojini nagar/06022014/4

I tried

URl.replace(" ", "%20")
URl.replaceAll(" ", "%20")
URL sourceUrl = new URL(url);
url = URLDecoder.decode(url, "UTF-8");

but it is not changing I do not know why.

Please help me..

With the URLDecoder one, it doesn't work because you have to encode , not decode:

url = URLEncoder.encode(url, "UTF-8");

For other examples you posted, you need to reassign the string:

url = url.replace(" ", "%20");
url = url.replaceAll(" ", "%20");

As Petter pointed out, URLEncoder.encode will add + instead of %20 . This is how URLEncoder works, but you can use

url = URLEncoder.encode(url, "UTF-8").replace("+","%20");

to make it work as you want.

Another option is to use the Uri class:

String url = "http://dli.ircms.in/complaint.php";
url = Uri.parse(url).buildUpon().appendQueryParameter("complaintno","sarojini nagar/06022014/4").build().toString();

Result:

http://dli.ircms.in/complaint.php?complaintno=sarojini%20nagar%2F06022014%2F4

您应该使用URLEncoder:

String url = URLEncoder.encode(url, "UTF-8");

If you are using the url in form of a string, a string is immutable so you have to assign the replaced string to a new one.

String url = theOriginalUrlString.replaceAll(" ", "%20");

The replacement is reflected in the new string.

Try this:

String url = "http://test.com/this is a test";
System.out.println(url);
url = url.replace(" ", "%20");
System.out.println(url);

or:

String url = URLEncoder.encode(url, "UTF-8");

Should be encode instead of decode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM