How to put a byte array into XML in Scala

2019-06-08 02:00发布

问题:

I'm interacting with a .Net web service. According to the service description the server is expecting a base64Binary type.

This is how I'm trying to build the SOAP packet:

  <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
    </soap:Header>
    <soap:Body>
      <uploadFile xmlns="http://localhost/">
        <FileDetails>
          <ReferenceNumber>123</ReferenceNumber>
          <FileName>testfile</FileName>
          <FullFilePath>file</FullFilePath>
          <FileType>1</FileType>
          <FileContents>{request.getContent().array()}</FileContents>
         </FileDetails>
        </uploadFile>
      </soap:Body>
   </soap:Envelope>

In the snippet above the request.getContent().array() is an HTTP request I'm receiving from a mobile application developed in PhoneGap.

The server responds that the FileContents is invalid. Any ideas?

回答1:

Your current version is just writing the bytes (I'm assuming request.getContent().array() is an array of bytes) as space-separated base-10 integers:

scala> val bytes = 1 to 10 map(_.toByte) toArray
bytes: Array[Byte] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> <FileContents>{bytes}</FileContents>
res0: scala.xml.Elem = <FileContents>1 2 3 4 5 6 7 8 9 10</FileContents>

This definitely isn't what you want. You can use a library like Apache Commons Codec to encode the byte array as a string (here I'm using the Base64 encoder):

scala> import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.binary.Base64

scala> <FileContents>{Base64.encodeBase64String(bytes)}</FileContents>
res1: scala.xml.Elem = <FileContents>AQIDBAUGBwgJCg==</FileContents>

You might have to tinker with the options a bit, but this is much more likely to be what you need.