Java非法base64字符20与来自PHP的base64字符串 - java

我用php生成PDF文件,并将php文件作为base64字符串返回,如下所示:

$base64 = base64_encode(file_get_contents("http://localhost/pdfgen" . $file));

我将其结果发送到应该发送邮件的Java服务器。

但是后来我得到了这个错误:

[error] a.a.OneForOneStrategy - Illegal base64 character 20
java.lang.IllegalArgumentException: Illegal base64 character 20
        at java.util.Base64$Decoder.decode0(Unknown Source)
        at java.util.Base64$Decoder.decode(Unknown Source)
        at java.util.Base64$Decoder.decode(Unknown Source)

我必须如何在java服务无法使用的php中对pdf文件进行编码。

提前致谢

更新:

我通过发布请求在我的ReactJs前端中调用php函数,该函数返回pdf作为base64编码的字符串。看起来像上面。

在前端,我再次向负责邮件服务的java后端发送帖子。

UPDATE Mail功能:

package scheduler

import java.util.Base64

import akka.actor.{Actor, ActorRef, ActorSystem}
import dto.email.models._
import dto.email.{emailDTO, emailLogDTO, smtpServerDTO}
import javax.inject.{Inject, Named}
import javax.mail.Message.RecipientType
import org.codemonkey.simplejavamail.{Email, MailException, Mailer, TransportStrategy}
import play.api.Configuration

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.util.Random

object EmailSendActor {

  case class Start(id: Int)

  trait Factory {
    def apply(): Actor
  }

}

class EmailSendActor @Inject()(
  implicit val executionContext: scala.concurrent.ExecutionContext,
  implicit val emailDTO: emailDTO,
  implicit val emailLogDTO: emailLogDTO,
  implicit val smtpServerDTO: smtpServerDTO,
  configuration: Configuration,
  val system: ActorSystem, @Named("email-send-scheduler") val schedulerActor: ActorRef
) extends Actor {

  import EmailSendActor._

  private val retryDelay = configuration.get[Int](EmailSchedulerActor.retryDelayKey)
  private val idlePause = configuration.get[Boolean](EmailSchedulerActor.idlePauseKey)
  private val simulateFailures = configuration.get[Boolean](EmailSchedulerActor.simulateFailuresKey)

  def receive: PartialFunction[Any, Unit] = {
    case x: Start =>
      println("Email Sender Running")
      schedulerActor ! EmailSchedulerActor.Busy(x.id)
      var emailCount = 0
      var retry = false

      val smtpServer = Await.result(smtpServerDTO.getGlobal, Duration.Inf)
      if (smtpServer.isDefined) {
        val globalSmtpServer = smtpServer.get

        println("Got Global Smtp Server " + globalSmtpServer)

        val result = emailDTO.getEmailsToSend(globalSmtpServer.smtpServerTypeId, retryDelay).map(emails => {
          emails.foreach { email =>
            emailCount += 1
            if (email.emailStatusTypeId == EmailStatusTypes.pending) {
              println("Sending new email[" + email.emailId + "]: " + email.recipients + ": " + email.subject)
              if (tryToSendEmail(globalSmtpServer, email)) retry = true
            } else if (email.emailStatusTypeId == EmailStatusTypes.retrying) {
              println("Retrying to send email[" + email.emailId + "]: " + email.recipients + ": " + email.subject)
              if (tryToSendEmail(globalSmtpServer, email)) retry = true
            }
          }
        })

        Await.result(result, Duration.Inf)
        if (emailCount > 0) {
          println("Done sending " + emailCount + " e-mails")
        } else {
          println("No e-mails to send")
        }
      } else {
        println("No Global Smtp Server Configurations, idling")
      }

      // reschedule next run
      if (retry) {
        schedulerActor ! EmailSchedulerActor.Retry(x.id)
      } else if (!idlePause || emailCount > 0) {
        schedulerActor ! EmailSchedulerActor.Done(x.id)
      } else {
        schedulerActor ! EmailSchedulerActor.Pause(x.id)
      }
  }

  private def tryToSendEmail(smtpServer: SmtpServerModel, email: EmailModel) = {
    var retry = false

    val sendResult = if (simulateFailures) Random.nextInt(5) else 0

    val result: (Future[Int], Future[Int]) = sendResult match {
      case 1 => // retry
        println("retrying")
        retry = true
        (emailDTO.updateEmailStatus(email.emailId.get, EmailStatusTypes.retrying),
          emailLogDTO.create(EmailLogModel(
            emailStatusTypeId = EmailStatusTypes.retrying,
            smtpServerId = smtpServer.smtpServerId.get,
            emailId = email.emailId.get,
            statusMessage = Option("Retrying")
          )))

      case 2 => // failed
        val status = Random.nextInt(EmailStatusTypes.retryTimeout - EmailStatusTypes.unknownDestination) + EmailStatusTypes.unknownDestination
        println("failed, status: " + status)
        (emailDTO.updateEmailStatus(email.emailId.get, status),
          emailLogDTO.create(EmailLogModel(
            emailStatusTypeId = status,
            smtpServerId = smtpServer.smtpServerId.get,
            emailId = email.emailId.get,
            statusMessage = Option("Failed randomly")
          )))

      case _ => // success
        val sendEmail = new Email()
        sendEmail.setFromAddress(smtpServer.fromName, smtpServer.fromEmail)
        sendEmail.setSubject(email.subject)

        val recipients: Option[Seq[EmailRecipient]] = EmailApi.getRecipients(email.recipients)
        if (recipients.isDefined) {
          recipients.get.foreach({ recipient =>
            sendEmail.addRecipient(recipient.name, recipient.email, RecipientType.TO)
          })
        }

        val ccRecipients: Option[Seq[EmailRecipient]] = EmailApi.getRecipients(email.ccRecipients)
        if (ccRecipients.isDefined) {
          ccRecipients.get.foreach({ recipient =>
            sendEmail.addRecipient(recipient.name, recipient.email, RecipientType.CC)
          })
        }

        val bccRecipients: Option[Seq[EmailRecipient]] = EmailApi.getRecipients(email.bccRecipients)
        if (bccRecipients.isDefined) {
          bccRecipients.get.foreach({ recipient =>
            sendEmail.addRecipient(recipient.name, recipient.email, RecipientType.BCC)
          })
        }

        var emailStatusTypeId = EmailStatusTypes.sent
        var statusMessage = "Sent"

        if (sendEmail.getRecipients.isEmpty) {
          emailStatusTypeId = EmailStatusTypes.unknownRecipient
          statusMessage = "No recipients"
        } else {
          if (email.isHtml.get) sendEmail.setTextHTML(email.body)
          else sendEmail.setText(email.body)

          if (!email.attachments.isEmpty) {
            val attachments: Option[Seq[EmailAttachment]] = EmailApi.getAttachments(email.attachments)
            if (attachments.isDefined) {
              attachments.get.foreach(attachment => {
                val bytes = Base64.getDecoder.decode(attachment.base64Content)
                sendEmail.addAttachment(attachment.name, bytes, attachment.mimeType)
              })
            }
          }

          try {
            new Mailer(smtpServer.address, smtpServer.port, smtpServer.username, smtpServer.password, smtpServer.smtpEncryptionTypeId match {
              case SmtpEncryptionTypes.none => TransportStrategy.SMTP_PLAIN
              case SmtpEncryptionTypes.ssl => TransportStrategy.SMTP_SSL
              case SmtpEncryptionTypes.tls => TransportStrategy.SMTP_TLS
            }).sendMail(sendEmail)

            println("email sent")
          } catch {
            case t: Throwable =>
              statusMessage = t.getMessage
              println(s"Send Failed with message $statusMessage")

              t match {
                case e: MailException =>
                  emailStatusTypeId = statusMessage match {
                    case OpenMailException.GENERIC_ERROR => EmailStatusTypes.serverError
                    case OpenMailException.MISSING_HOST => EmailStatusTypes.serverError
                    case OpenMailException.MISSING_USERNAME => EmailStatusTypes.unknownRecipient
                    case OpenMailException.INVALID_ENCODING => EmailStatusTypes.serverError
                    case OpenMailException.INVALID_RECIPIENT => EmailStatusTypes.unknownRecipient
                    case OpenMailException.INVALID_REPLYTO => EmailStatusTypes.serverError
                    case OpenMailException.INVALID_SENDER => EmailStatusTypes.serverError
                    case OpenMailException.MISSING_SENDER => EmailStatusTypes.serverError
                    case OpenMailException.MISSING_RECIPIENT => EmailStatusTypes.unknownDestination
                    case OpenMailException.MISSING_SUBJECT => EmailStatusTypes.serverError
                    case OpenMailException.MISSING_CONTENT => EmailStatusTypes.serverError
                    case _ => EmailStatusTypes.serverError
                  }

                case _ => EmailStatusTypes.serverError
              }
          }
        }

        (emailDTO.updateEmailStatus(email.emailId.get, emailStatusTypeId),
          emailLogDTO.create(EmailLogModel(
            emailStatusTypeId = emailStatusTypeId,
            smtpServerId = smtpServer.smtpServerId.get,
            emailId = email.emailId.get,
            statusMessage = Option(statusMessage)
          )))
    }

    Await.result(result._1, Duration.Inf)
    Await.result(result._2, Duration.Inf)
    retry
  }
}

错误在这一行:

val bytes = Base64.getDecoder.decode(attachment.base64Content)

参考方案

我解决了:

pdf.trim()

现在我有一个有效的base64,并且一切正常。

页面加载而不是提交时发生struts验证 - java

请原谅我;我对Struts有点陌生。我遇到一个问题,即页面加载而不是我实际提交表单时发生了验证。我整天都在论坛上搜寻和搜寻,没有任何运气。我显然做错了一些事情,应该很容易确定,但是我还没有发现问题所在。这是我的struts.xml的片段:<action name="*Test" method="{1}" clas…

DataSourceTransactionManager和JndiObjectFactoryBean和JdbcTemplate的用途是什么? - java

以下的用途是什么:org.springframework.jdbc.core.JdbcTemplate org.springframework.jdbc.datasource.DataSourceTransactionManager org.springframework.jndi.JndiObjectFactoryBean <tx:annotatio…

当回复有时是一个对象有时是一个数组时,如何在使用改造时解析JSON回复? - java

我正在使用Retrofit来获取JSON答复。这是我实施的一部分-@GET("/api/report/list") Observable<Bills> listBill(@Query("employee_id") String employeeID); 而条例草案类是-public static class…

JAVA:如何检查对象数组中的所有对象是否都是子类的对象? - java

我有一个对象数组。现在,我要检查所有这些对象是否都是MyObject的实例。有没有比这更好的选择:boolean check = true; for (Object o : justAList){ if (!(o instanceof MyObject)){ check = false; break; } } java大神给出的解决方案 如果您不喜欢循环,则…

SOAPFaultException部署在Tomcat上时,但在GlassFish中工作正常 - java

朋友们,我一直在尝试很多,阅读了很多论坛,但无法理解为什么出现此问题。我使用契约优先方法创建了一个Jax-WS WebService。创建WSDL和XSD,然后使用wsimport工具生成其余工件,为SEI提供实现。将WebService应用程序部署到Eclipse Helios中的GlassFish(Glassfish适配器和Eclipse中安装的插件)。…