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!

2
  • 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 = "stackoverflow.com/search?q=" + query;. Look at this answer link Commented Apr 2, 2015 at 17:25
  • I did not know you could encode a string to utf-8. Thanks! Commented Apr 8, 2015 at 16:12

4 Answers 4

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;
   }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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!

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.