Jaume
Jaume

Reputation: 3780

android UTF8 encoding from received string

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

Upvotes: 11

Views: 39100

Answers (3)

Martin Stone
Martin Stone

Reputation: 13007

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

String s = URLDecoder.decode(myString, "UTF-8");

Upvotes: 23

Jorgesys
Jorgesys

Reputation: 126455

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"

Upvotes: 4

nullpotent
nullpotent

Reputation: 9260

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();
}

Upvotes: 4

Related Questions