android java URLDecoder problem - android

i have a String displayed on a WebView as "Siwy & Para Wino"
i fetch it from url , i got a string "Siwy%2B%2526%2BPara%2BWino". // be corrected
now i'm trying to use URLDecoder to solve this problem :
String decoded_result = URLDecoder.decode(url); // the url is "Siwy+%26+Para+Wino"
then i print it out , i still saw "Siwy+%26+Para+Wino"
Could anyone tell me why?

From the documentation (of URLDecoder):
This class is used to decode a string which is encoded in the application/x-www-form-urlencoded MIME content type.
We can look at the specification to see what a form-urlencoded MIME type is:
The form field names and values are escaped: space characters are replaced by '+', and then reserved characters are escaped as per [URL]; that is, non-alphanumeric characters are replaced by '%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks, as in multi-line text field values, are represented as CR LF pairs, i.e. '%0D%0A'.
Since the specification calls for a percent sign followed by two hexadecimal digits for the ASCII code, the first time you call the decode(String s) method, it converts those into single characters, leaving the two additional characters 26 intact. The value %25 translates to % so the result after the first decoding is %26. Running decode one more time simply translates %26 back into &.
String decoded_result = URLDecoder.decode(URLDecoder.decode(url));
You can also use the Uri class if you have UTF-8-encoded strings:
Decodes '%'-escaped octets in the given string using the UTF-8 scheme.
Then use:
String decoded_result = Uri.decode(Uri.decode(url));

thanks for all answers , i solved it finally......
solution:
after i used URLDecoder.decode twice (oh my god) , i got what i want.
String temp = URLDecoder.decode( url); // url = "Siwy%2B%2526%2BPara%2BWino"
String result = URLDecoder.decode( temp ); // temp = "Siwy+%26+Para+Wino"
// result = "Swy & Para Wino". !!! oh good job.
but i still don't know why.. could someone tell me?

Related

I get fields of type String with some Unicode characters instead of the usual

My problem is that I am getting strings where some characters are Unicode.
"fieldName": "Ac6jHguQjKKUxx6MSOpjO2kOLKPAdjStVs1pgTGNSU8\u003d"
Then I immediately send such a string to another API and the server returns me an error with a code of 500. If I use this string in postman and replace the unicode with a normal one, then the code 200 is returned from the server.
I thought there was a problem in the server, but they checked it and said that they were sending it as expected.
How do I translate Unicode?
The easiest way is to use URLDecoder. Here is an example.
String str = "Ac6jHguQjKKUxx6MSOpjO2kOLKPAdjStVs1pgTGNSU8\u003d";
String decode = URLDecoder.decode(str, "UTF-8");
System.out.println(decode);
//Ac6jHguQjKKUxx6MSOpjO2kOLKPAdjStVs1pgTGNSU8=

base64 decode string and encode all special characters lost

I have a Java class which I convert to string using GSON. Post this the string is base64 encoded (for some reason, lets not go there :) ) When I decode it back I lose all { and " " characters in json.
For example: {"name":"ABC"} decoded and encoded back becomes nameABC
I want to get my old data back i.e I want {"name:"ABC"} back
String json = "{\"name\":\"ABC\"}";
byte en[] = android.util.Base64.decode(json,Base64.NO_WRAP);
String st = android.util.Base64.encodeToString(en,Base64.NO_WRAP);
Something as simple as above, content is lost
Please help
You can't Base64 has set 64 characters that can converted to binary and vice versa, characters like { and " is not in the 64 set of characters check this
Try using URLDecoder with UTF-8 or any other encoding method which support UTF-8

Add new line character in remote config text

I'm doing Firebase RemoteConfig integration. In one of the scenarios, I need to break a text line, so I tried to use new line character (\n).
But this is not working, it is neither displaying as an extra character nor creating another line.
My solution is replace \n manually (assuming that in Firebase Console you put property for TITLE as "Title\nNewLine"):
FirebaseRemoteConfig.getInstance().getString(TITLE).replace("\\n", "\n")
Try using an uncommon character like two pipes || and then replacing every occurance of those with a newline after you do getString() in the code.
You can insert encoded text(with Base64) to Firebase panel.
After, decode the String from your Java class and use it.
Like
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");
The trick (which actually works for all HTML tags supported on your target platform) is to wrap the String in a JSON Object on RemoteConfig, like so:
{
"text":"Your text with linebreaks...<br><br>...as well as <b>bold</b> and <i>italic</i> text.
}
On the target platform you then need to parse the JSON and convert it back to a simple string. On Android this looks like this:
// extract value from JSON
val text = JSONObject(remoteConfig.getString("remoteConfig_key")).getString("text")
// create Spanned and use it
view.text = HtmlCompat.fromHtml(text)
So what worked for me is to use "||" (or some other character combination you are confident will not be in the string) as the new line character. Then replace "||" with "\n". This string will then display properly for me.
For some reason sending "\n" in the string doesn't get recognized as expected but adding it manually on the receiving side seems to work.
To make the suggestion mentioned above, you can try this code(that can be generalized to "n" number of elements). Simply replace the sample text with yours with the same format and add the amount of elements
String text="#Elemento1#Elemento2#Elemento3#";
int cantElementos=3;
arrayElementosFinales= new String[cantElementos];
int posicionNum0=0;
int posicionNum1;
int posicionNum2;
for(int i=0;i<cantElementos;i++){
posicionNum1=text.indexOf("#",posicionNum0);
posicionNum2=text.indexOf("#", posicionNum1+1);
char [] m = new char[posicionNum2-posicionNum1-1];
text.getChars(posicionNum1+1, posicionNum2,m,0);
arrayElementosFinales[i]=String.valueOf(m);
posicionNum0=posicionNum2;
}
Use Cdata in the remote config in combination with "br" tag and HTML.fromHtml() .. for eg.
<![CDATA[ line 1<br/>line 2]]>

why #character is missing while i split string using comma(,) in andorid?

1.here i want same string as on xml format but while i store into array it missed # from the string and added space
<string xmlns="http://tempuri.org/">7633,abcd#123</string>
loginDetailsArray = loginDetails.split(",");
intPersonID = loginDetailsArray[0];
strPassword = loginDetailsArray[1];
separeted using comma
resultstring=abcd 123//# is missing
You can try to replace # or any special characters with equivalent sign;
However you may not change password charactres.
Your SMS API might be not allowing passing Special characters.
You does not encode character '#'. Encode it ->
#amp;

In Android how to concatenate base64 encoded strings?

Please help me to solve this:
I have two strings for email-id and password like
String name = "xyz#gmail.com";
String pass = "abc";
I encode these two into Base64 string like
String encoded_name = new String(Base64.encode(name.getBytes(), 0));
String encoded_pass = new String(Base64.encode(pass.getBytes(), 0));
and I need to concatenate these two encoded strings with space like
String merge = encoded_name + " " + encoded_pass;
I checked this string in console by
System.out.print("Concatenate string= " + merge);
but in console I am getting result in two lines like this
11-18 00:25:29.898: INFO/System.out(1244): Merge= eHl6QGdtYWlsLmNvbQ==
11-18 00:25:29.908: INFO/System.out(1244): YWJj
Why is this happing the result is unexpected for me why it is not printing in a single line. please help me to solve this.
Thanks
You should use the NO_WRAP flag as described in the Docs, the Base64 class will not add additional newlines.
NO_WRAP: Encoder flag bit to omit all line terminators (i.e., the output will be on one long line).
So change your lines to the following:
String encoded_name = new String(Base64.encode(name.getBytes(), Base64.NO_WRAP));
String encoded_pass = new String(Base64.encode(pass.getBytes(), Base64.NO_WRAP));
This will output the following:
11-17 19:16:51.283: INFO/System.out(354): Concatenate string= eHl6QGdtYWlsLmNvbQ== YWJj
Please have a look on Android Api reference Document. It will solve all other queries regarding Base64 encoding/decoding in android.
one more efficient way to solve your problem:
String encoded_name = Base64.encodeToString(name.getBytes("utf-8"), Base64.NO_WRAP);
String encoded_pass = Base64.encodeToString(pass.getBytes("utf-8"), Base64.NO_WRAP);
out put:-
11-17 10:55:27.492: V/BASE-64-.encodeToString(525): eHl6QGdtYWlsLmNvbQ== YWJj
Look at this doc, the mime section states that
MIME does not specify a fixed length for Base64-encoded lines, but it does specify a maximum line length of 76 characters. Additionally it specifies that any extra-alphabetic characters must be ignored by a compliant decoder, although most implementations use a CR/LF newline pair to delimit encoded lines.
You should only consider removing the last char of your first base 64 string, it seems to be a \n (a more generic method would be to test wether it is or not.)
Regards,
Stéphane

Categories

Resources