java Android的PHP/Java之间的数据编码/解码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15156811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Encoding/decoding of data between PHP/Java for Android
提问by Ronnie
I have to decode a base64 encoded data received from a PHP server.
我必须解码从 PHP 服务器接收到的 base64 编码数据。
The server uses 'base64_encode' to encode the data.
服务器使用“base64_encode”对数据进行编码。
In my Android app, I use android.utils.Base64 class to do the decoding.
在我的 Android 应用程序中,我使用 android.utils.Base64 类进行解码。
original encrypted data = "?+ü]M(?=??"
Base64 encoding data in PHP gives - "hisP3F1NBCgIAocQCD3x9g=="
Base64 encoding data in Android gives - "4oCgKw/DnF1NBCgIAuKAoRAIPcOxw7Y="
原始加密数据 = "?+ü]M(?=??"
PHP 中的 Base64 编码数据给出 - "hisP3F1NBCgIAocQCD3x9g=="
Android 中的 Base64 编码数据给出 - "4oCgKw/DnF1NBCgIAuKAoRAIPcOxw7Y="
As you can see, the Java encoded string is longer than the PHP encoded string. I need to find out their default encoding formats.
如您所见,Java 编码的字符串比 PHP 编码的字符串长。我需要找出他们的默认编码格式。
How to get the same encoded string from both?
如何从两者中获取相同的编码字符串?
Java/Android code :
Java/Android 代码:
String encrypted = "?+ü]M(?=??";
byte[] encoded = Base64.encode(encrypted.getBytes(), Base64.DEFAULT);
String str = new String(encoded); //str = "4oCgKw/DnF1NBCgIAuKAoRAIPcOxw7Y="
回答by Shehabic
Try this in Java: This will give you the long version of the string (UTF-8)
在 Java 中试试这个:这会给你字符串的长版本 (UTF-8)
byte[] encoded = Base64.encode(encrypted.getBytes("UTF-8"), Base64.DEFAULT);
String str = new String(encoded, "UTF-8");
Updated:
更新:
Try this in Java: This will give you the short version of the string (CP1252)
在 Java 中试试这个:这会给你字符串的简短版本 (CP1252)
// This should give the same results as in PHP
byte[] encoded = Base64.encode(encrypted.getBytes("CP1252"), Base64.DEFAULT);
String str = new String(encoded, "CP1252");
Alternatively try this PHP Script:
或者试试这个 PHP 脚本:
file: test.php
文件:test.php
<?php
echo base64_encode($_GET['str'])." Default UTF-8 version<br />";
echo base64_encode(iconv("UTF-8","CP1252",$_GET['str']))." CP1252 Version <br />";
?>
usage: http://[SOMEDOMAIN]/test.php?str=?+ü]M(?=??
回答by Gismo Ranas
For me CP1252 didn't work because it failed with non alphanumeric symbols. The best charset I found is ISO-8859-1, use as follows:
对我来说,CP1252 不起作用,因为它因非字母数字符号而失败。我找到的最好的字符集是 ISO-8859-1,使用如下:
Base64.getEncoder()
.encodeToString(
stringToBeEncoded.getBytes(
Charset.forName("ISO-8859-1")))