Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android UTF8 encoding from received string

Tags:

java

android

I am receiving a string that is not properly encoded like mystring%201, where must be mystring 1. How could I replace all characters that could be interpreted as UTF8? I read a lot of posts but not a full solution. Please note that string is already encoded wrong and I am not asking about how to encode char sequence. I asked same issue for iOS few days ago and was solved using stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding. Thank you.

ios UTF8 encoding from nsstring

like image 898
Jaume Avatar asked Aug 20 '12 15:08

Jaume


People also ask

Does Android use UTF-8?

The default character encoding for Android is UTF-8, as specified by the JavaDoc of the Charset. defaultCharset() method. It can be validated by calling that same method.

What is StandardCharsets UTF_8 in Java?

Introduction. When working with Strings in Java, we oftentimes need to encode them to a specific charset, such as UTF-8. UTF-8 represents a variable-width character encoding that uses between one and four eight-bit bytes to represent all valid Unicode code points.


3 Answers

I am receiving a string that is not properly encoded like "mystring%201

Well this string is already encoded, you have to decode:

String sDecoded = URLDecoder.decode("mystring%201", "UTF-8");

so now sDecoded must have the value of "mystring 1".

The "Encoding" of String:

String sEncoded = URLEncoder.encode("mystring 1", "UTF-8");

sEncoded must have the value of "mystring%201"

like image 108
Jorgesys Avatar answered Nov 08 '22 14:11

Jorgesys


You can use the URLDecoder.decode() function, like this:

String s = URLDecoder.decode(myString, "UTF-8");
like image 27
Martin Stone Avatar answered Nov 08 '22 13:11

Martin Stone


Looks like your string is partially URL-encoded, so... how about this:

try {
 System.out.println(URLDecoder.decode("mystring%201", "UTF-8"));
} catch(UnsupportedEncodingException e) {
 e.printStackTrace();
}
like image 25
nullpotent Avatar answered Nov 08 '22 12:11

nullpotent