2008-09-16 108 views

回答

4

雖然這個例子不是可編譯和完整的,但其基本思想是告訴kSOAP如何將XML標記轉換爲對象(即readInstance())以及如何將對象轉換爲XML標記即writeInstance())。

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。

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編碼來封送File對象。

+0

你能提供完整的源代碼嗎? – Rajapandian 2009-08-13 11:00:28