首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要kSOAP编组帮助

需要kSOAP编组帮助
EN

Stack Overflow用户
提问于 2008-09-16 21:09:10
回答 1查看 4.8K关注 0票数 3

有没有人有一个使用kSOAP包的很好的复杂对象编组示例?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2008-09-17 23:26:49

尽管这个示例不是可编译的和完整的,但其基本思想是有一个类告诉kSOAP如何将XML标记转换为对象(即readInstance())以及如何将对象转换为XML标记(即writeInstance())。

代码语言:javascript
复制
public class MarshalBase64File implements Marshal {

  public static Class FILE_CLASS = File.class;

  public Object readInstance(XmlPullParser parser, String namespace, String name, PropertyInfo expected)
      throws IOException, XmlPullParserException {
    return Base64.decode(parser.nextText());
  }

  public void writeInstance(XmlSerializer writer, Object obj) throws IOException {
    File file = (File)obj;
    int total = (int)file.length();
    FileInputStream in = new FileInputStream(file);
    byte b[] = new byte[4096];
    int pos = 0;
    int num = b.length;
    if ((pos + num) > total) {
      num = total - pos;
    }
    int len = in.read(b, 0, num);
    while ((len != -1) && ((pos + len) < total)) {
      writer.text(Base64.encode(b, 0, len, null).toString());
      pos += len;
      if ((pos + num) > total) {
        num = total - pos;
      }
      len = in.read(b, 0, num);
    }
    if (len != -1) {
      writer.text(Base64.encode(b, 0, len, null).toString());
    }
  }

  public void register(SoapSerializationEnvelope cm) {
    cm.addMapping(cm.xsd, "base64Binary", MarshalBase64File.FILE_CLASS, this);
  }
}

稍后,当您调用SOAP服务时,您将把对象类型(在本例中为File对象)映射到编组类。SOAP信封将自动匹配每个参数的对象类型,如果它不是内置类型,则调用关联的封送处理程序将其转换为XML或从XML转换为XML。

代码语言:javascript
复制
public class MarshalDemo {

  public String storeFile(File file) throws IOException, XmlPullParserException {
    SoapObject soapObj = new SoapObject("http://www.example.com/ws/service/file/1.0", "storeFile");
    soapObj.addProperty("file", file);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    new MarshalBase64File().register(envelope);
    envelope.encodingStyle = SoapEnvelope.ENC;
    envelope.setOutputSoapObject(soapObj);

    HttpTransport ht = new HttpTransport(new URL(server, "/soap/file"));
    ht.call("http://www.example.com/ws/service/file/1.0/storeFile", envelope);

    String retVal = "";
    SoapObject writeResponse = (SoapObject)envelope.bodyIn;
    Object obj = writeResponse.getProperty("statusString");
    if (obj instanceof SoapPrimitive) {
      SoapPrimitive statusString = (SoapPrimitive)obj;
      String content = statusString.toString();
      retVal = content;
    }
    return retVal;
  }
}

在本例中,我使用Base64编码来编组文件对象。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/77131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档