How to put a byte array into XML in Scala

核能气质少年 提交于 2019-12-12 10:15:03

问题


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.



来源:https://stackoverflow.com/questions/9739473/how-to-put-a-byte-array-into-xml-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!