Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTF-8 conversion in Android?

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?

like image 637
Praveen Avatar asked Oct 21 '11 06:10

Praveen


3 Answers

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

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

like image 69
frayab Avatar answered Oct 17 '22 15:10

frayab


Just try it:

URLEncoder.encode(str, "UTF-8");
like image 45
Paresh Mayani Avatar answered Oct 17 '22 15:10

Paresh Mayani


You can use this:

import java.net.URLEncoder;

class{
    String TEXT;

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

}
like image 30
Ricardo Centeno Lugo Avatar answered Oct 17 '22 15:10

Ricardo Centeno Lugo