如何在Scala中将字节数组放入XML

如何在Scala中将字节数组放入XML

本文介绍了如何在Scala中将字节数组放入XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与.Net Web服务进行交互。根据服务描述,服务器正在等待一个base64Binary类型。

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

这是我尝试构建SOAP包的方式:

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>

request.getContent / code>是从PhoneGap中开发的移动应用程序接收的HTTP请求。

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

服务器响应FileContents无效。任何想法?

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

推荐答案

您当前的版本只是写字节(我假设 request.getContent ().array()是一个以空格分隔的10进制整数的字节数组:

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.

这篇关于如何在Scala中将字节数组放入XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 13:58