【问题标题】:Encode/decode Base64 fails编码/解码 Base64 失败
【发布时间】:2018-07-25 05:36:54
【问题描述】:

在我的应用程序客户端-服务器中,在客户端我以以下格式发送文件内容:

public static String getImageFromURI (Context contesto, Uri uri) {
    InputStream is;
    ByteArrayOutputStream bos;
    try {
        is = contesto.getContentResolver().openInputStream(uri);
        bos = new ByteArrayOutputStream();

        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = is.read(buf)) != -1;) {
                bos.write(buf, 0, readNum); //no doubt here is 0
            }
        } catch (IOException ex) {
            Log.d("TAG_F2S", "Sono nel catch IOExcetion con emssage = " + ex.getMessage());
            ex.printStackTrace();
            return null;
        }

        return new String (Base64.encode(bos.toByteArray(), Base64.DEFAULT), "UTF-8");
    } catch (FileNotFoundException fnfe) {
        Log.d("TAG_F2S", "Sono nel catch FileNotFoundExcetion con emssage = " + fnfe.getMessage());
        fnfe.printStackTrace();

        return null;
    } catch (UnsupportedEncodingException uee) {
        Log.d("TAG_F2S", "Sono nel catch UnsupportedEncodingExcetion con emssage = " + uee.getMessage());
        uee.printStackTrace();

        return null;
    }
}

在服务器端,我尝试按如下方式创建文件:

byte [] byteFile = java.util.Base64.getDecoder ().decode(contenuto.getBytes("UTF-8"));

Files.write(Paths.get(myPath), byteFile);

但我无法获得结果导致这样的异常:

java.lang.IllegalArgumentException: Illegal base64 character a
at java.util.Base64$Decoder.decode0(Unknown Source)
at java.util.Base64$Decoder.decode(Unknown Source)
....

我的错误是什么?我不明白。。 感谢您的帮助。


编辑: 我发送到服务器的字符串如下: https://codeshare.io/GqQWNA

【问题讨论】:

  • 我想知道,contenuto.getBytes("UTF-8") 在您的示例中返回什么?
  • 失败时尝试解码的字符串是什么?
  • @GregT 我编辑了我的帖子
  • @AndreasHartmann 看到我的编辑,谢谢
  • 你确定那是base64吗?尝试使用在线解码器对其进行解码会导致文件损坏

标签: java android utf-8 base64


【解决方案1】:

我发现了问题:

当我对文件内容进行编码并在 POST 请求中将数据发送到服务器时,内容被修改,仅将所有“+”字符替换为“”(空格)。 在服务器端执行以下操作:

java.util.Base64.getMimeDecoder().decode(contenuto.replace(" ", "+"));

我没有问题。注意我用的是getMimeDecoder而不是getDecoder,否则不起作用。

有人知道这个问题的原因吗?

【讨论】:

猜你喜欢
  • 2018-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多