UTF-8 conversion in Android?

11,252

Solution 1

For UTF encoding use this -> URLEncoder.encode(string, "UTF-8");

Also you need to change spaces -> string.replace(" ", "%20");

Solution 2

Just try it:

URLEncoder.encode(str, "UTF-8");

Solution 3

You can use this:

import java.net.URLEncoder;

class{
    String TEXT;

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

}
Share:
11,252
Praveen
Author by

Praveen

Android, iOS and React Native Developer

Updated on July 23, 2022

Comments

  • Praveen
    Praveen over 1 year

    I am encountering a problem that I need to call a web service. I just need to generate a UTF-8 encoded url string. Because the parameter may contain spaces, I am using below piece of code to encode to utf-8:

    public String encodeUTF(String str) {
    
            try {
                byte[] utf8Bytes = str.getBytes("UTF-8");
    
                String encodedStr = new String(utf8Bytes, "UTF-8");
    
                return encodedStr;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return str;
        }
    

    But still I am getting the same value. Because of this I am getting illegal argument exception while calling the service. Any ideas?

  • Praveen
    Praveen about 12 years
    now i am not getting illeagal argument exception. but i got http response exception: bad request . do you have any idea?