1

Working on an android app that makes a HTTP request based on user input.

I want to achieve the following String as part of an HTTP request:

The%20Cat%20Sat

User input to an EditText:

The Cat Sat

I understand the string needs to be split and placed into an array, however it must then accept %20 after each entered word, before being converted back to a string.

Any guidance would be great!

carteruk
  • 129
  • 1
  • 2
  • 9
  • Why did you want to Split String to Array? You can encode the user input like this. String query = URLEncoder.encode("The Cat Sat", "utf-8"); String url = "http://stackoverflow.com/search?q=" + query;. Look at this answer [link](http://stackoverflow.com/a/3286128/3512164) – Ibrahim Disouki Apr 02 '15 at 17:25
  • I did not know you could encode a string to utf-8. Thanks! – carteruk Apr 08 '15 at 16:12

4 Answers4

1

You can use this method, which rely on URLEncoder class:

public static String urlEncodeString(String s){
   try {
       return URLEncoder.encode(s,"UTF-8");
   }
   catch (  UnsupportedEncodingException e) {
       return s;
   }
}
bonnyz
  • 13,458
  • 5
  • 46
  • 70
0

You could a) unescape the string.

java.net.URLDecoder.decode("The%20Cat%20Sat", "UTF-8");

or remove the %20 and split it.

String[] array = "The%20Cat%20Sat".split("%20");

and then when you get it back

for (String str : array) {
    str.replace("%20", "");
}

or replace all and replace with a space by using:

"The%20Cat%20Sat".replaceAll(" ","%20");

but you should consider using decode and encode which is in most cases the proper way doing it.

Emanuel
  • 8,027
  • 2
  • 37
  • 56
0

Use URLEncoder.encode() and URLDecoder.decode() for making user input safe for HTTP URL's and vice versa. Remember it's not only spaces you have to worry about but special characters too. URLEncoder is the only safe way!

Samuel
  • 16,923
  • 6
  • 62
  • 75
0

you can replace spaces of your string with %20 to get the desired output.

String myString = myEditText.getText().toString();
myString=myString.replaceAll(" ","%20");