2011-07-23 70 views
0

我想將xml文件發送到.net web服務,但它不起作用。在我的項目中,我使用DOM Object創建了xml文件。我想發送該Dom對象到服務器,但它沒有工作。如何將xml文件發送到.net web服務中android

我還在我的項目中使用了Ksoap2 jar文件。請幫助我如何將xml文件發送到.net服務器。這裏是我的代碼:

package com.Android.Xml; 

import java.io.InputStream; 
import java.io.StringWriter; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.ParserConfigurationException; 
import javax.xml.transform.Transformer; 
import javax.xml.transform.TransformerConfigurationException; 
import javax.xml.transform.TransformerException; 
import javax.xml.transform.TransformerFactory; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 

import org.ksoap2.SoapEnvelope; 
import org.ksoap2.serialization.PropertyInfo; 
import org.ksoap2.serialization.SoapObject; 
import org.ksoap2.serialization.SoapPrimitive; 
import org.ksoap2.serialization.SoapSerializationEnvelope; 
import org.ksoap2.transport.HttpTransportSE; 
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 

public class BuildAndSend extends Activity { 

    private static final String METHOD_NAME = "SaveXmlData"; 
    private static final String NAMESPACE = "http://tempuri.org/"; 
    //private static final String URL = "http://61.12.109.69/AndroidWebservice/Service.asmx"; 
    private static final String URL = "http://192.168.0.51/WebServiceExample/Service.asmx"; 
    final String SOAP_ACTION = "http://tempuri.org/SaveXmlData"; 
    TextView tv; 
    Button send; 
    StringBuilder sb; 
    Document doc; 
    DOMSource source; 
    StringWriter writer ; 
    InputStream inputStream; 
    /** Called when the activity is first created. */ 
    String[] input = {"", ""}; 
    String[] line = new String[2]; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     sb = new StringBuilder(); 
     tv=(TextView)findViewById(R.id.text); 
     send=(Button)findViewById(R.id.button1); 
     send.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       call(); 
      } 
     }); 

     DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder; 
     try { 
      builder = factory.newDocumentBuilder(); 
      doc = builder.newDocument(); 
      Element root = doc.createElement("root"); 
      doc.appendChild(root); 
      //Element memberList = doc.createElement("members"); 
      // root.appendChild(memberList); 

      for (int i = 0; i < input.length; i++) { 
       line = input[i].split(","); 

       Element member = doc.createElement("member"); 
       root.appendChild(member); 

       Element name = doc.createElement("name"); 

       name.appendChild(doc.createTextNode(line[0])); 
       member.appendChild(name); 

       Element phone = doc.createElement("phone"); 
       phone.appendChild(doc.createTextNode(line[1])); 
       member.appendChild(phone); 
      } 

      TransformerFactory tFact = TransformerFactory.newInstance(); 
      Transformer trans; 

       try { 
        trans = tFact.newTransformer(); 
        writer = new StringWriter(); 
        StreamResult result = new StreamResult(writer); 
        source = new DOMSource(doc); 
        trans.transform(source, result); 
        System.out.println(writer.toString()); 
        // call(); 
       } catch (TransformerConfigurationException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } catch (TransformerException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

     } catch (ParserConfigurationException e) { 
      e.printStackTrace(); 
     } 
    }  
    public void call() { 
     try { 

      SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
      PropertyInfo p=new PropertyInfo(); 
      p.setName("XmlFile"); 
      p.setValue(doc); 
      p.setType(Document.class); 
      request.addProperty(p); 
      SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
      envelope.dotNet = true; 
      envelope.setOutputSoapObject(request); 
      HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); 
      androidHttpTransport.call(SOAP_ACTION, envelope); 
      SoapPrimitive result = (SoapPrimitive)envelope.getResponse();   
      String resultData = result.toString(); 
      sb.append(resultData + "\n"); 
      } catch (Exception e) { 
      sb.append("Error:\n" + e.getMessage() + "\n"); 
      System.out.println("error::::::::"+e.getMessage()); 
      } 


     } 
} 

回答

0

我建議你寫一個數據類,並將你的XML文件反序列化爲它的一個實例。 (JAXB自動化了這個過程,但據我所知,你不能在Android上使用JAXB,所以你需要編寫你自己的解析器。)然後把這個對象傳遞給你的.NET Web服務,然後在服務器端再次將它序列化爲XML .NET XMLSerializer。調用.NET Web或WCF服務時,您可以使用k-soap2傳遞自定義類。

例如你有一個像下面的XML文件: <person> <name>xyz</name> <surname>abc</surname> <age>30</age> </person> 在服務器端創建一個Person類都與名字,姓氏和年齡屬性的客戶端。然後將您的xml文件解析到客戶端的Person類實例。現在您可以將您的Person實例發送到您的Web服務。在這種情況下,您當然需要編輯您的Web服務,以便它可以接受您的類型(在本例中爲Person)。

如果您還有其他問題,請告訴我。上傳

+0

嗨感謝responce.But我不明白你在說什麼。你能舉個例子嗎? – user859255

0
** 

代碼中動態創建的XML從SD卡中的Android到weservice:

**

package com.example.xmlfilecreator; 

    import java.io.File; 
    import java.io.FileNotFoundException; 
    import java.io.FileOutputStream; 
    import java.io.IOException; 

    import org.apache.http.HttpEntity; 
    import org.apache.http.HttpResponse; 
    import org.apache.http.client.HttpClient; 
    import org.apache.http.client.methods.HttpPost; 
    import org.apache.http.entity.mime.MultipartEntity; 
    import org.apache.http.entity.mime.content.FileBody; 
    import org.apache.http.entity.mime.content.StringBody; 
    import org.apache.http.impl.client.DefaultHttpClient; 
    import org.apache.http.util.EntityUtils; 
    import org.xmlpull.v1.XmlSerializer; 

    import android.app.Activity; 
    import android.os.Bundle; 
    import android.os.Environment; 
    import android.util.Log; 
    import android.util.Xml; 
    import android.view.View; 
    import android.view.View.OnClickListener; 
    import android.widget.Button; 
    import android.widget.TextView; 

    public class XmlFileCreator extends Activity implements OnClickListener { 
     public int i=0; 
     Button b3; 
     HttpEntity resEntity; 
     public TextView tv; 
     public String filename=""; 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 
      b3 = (Button)findViewById(R.id.upload); 
      tv = (TextView)findViewById(R.id.tv); 
      b3.setOnClickListener(this); 
      filename="addupload.xml"; 
      String[] no = new String[] { 
        "1", 
        "2", 
        "3", 
        "4", 
        "5", 

       }; 
      String[] questype = new String[] { 
        "add 2 nos", 
        "add 3 nos", 
        "add 2 nos", 
        "add 3 nos", 
        "add 5 nos",  
       }; 
      String[] ques = new String[] { 
        "2+2", 
        "3+3", 
        "4+4", 
        "5+5", 
        "6+6",  
       }; 
      String[] cans = new String[] { 
        "4", 
        "6", 
        "8", 
        "10", 
        "12",  
       }; 
      String[] uans = new String[] { 
        "4", 
        "5", 
        "8", 
        "9", 
        "10",  
       }; 
      //create a new file called "new.xml" in the SD card 
      File newxmlfile = new File(Environment.getExternalStorageDirectory()+"/"+filename); 
      try{ 
       newxmlfile.createNewFile(); 
      }catch(IOException e){ 
       Log.e("IOException", "exception in createNewFile() method"); 
      } 
      //we have to bind the new file with a FileOutputStream 
      FileOutputStream fileos = null;   
      try{ 
       fileos = new FileOutputStream(newxmlfile); 
      }catch(FileNotFoundException e){ 
       Log.e("FileNotFoundException", "can't create FileOutputStream"); 
      } 
      //we create a XmlSerializer in order to write xml data 
      XmlSerializer serializer = Xml.newSerializer(); 
      try { 
       //we set the FileOutputStream as output for the serializer, using UTF-8 encoding 
       serializer.setOutput(fileos, "UTF-8"); 
       //Write <?xml declaration with encoding (if encoding not null) and standalone flag (if standalone not null) 
       serializer.startDocument(null, Boolean.valueOf(true)); 
       //set indentation option 
       serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 
       //start a tag called "root" 
        serializer.startTag(null, "Worksheet"); 
        while(i<no.length) 
        { 
       //i indent code just to have a view similar to xml-tree 
         serializer.startTag(null, "Question"); 
         //set an attribute called "attribute" with a "value" for <child2> 
         serializer.attribute(null, "number", no[i]); 
         serializer.endTag(null, "Question"); 

         serializer.startTag(null, "QuestionType"); 
         //write some text inside <child3> 
         serializer.text(questype[i]); 
         serializer.endTag(null, "QuestionType"); 


         serializer.startTag(null, "Question"); 
         serializer.text(ques[i]); 
         serializer.endTag(null, "Question"); 

         serializer.startTag(null, "CorrectAnswer"); 
         serializer.text(cans[i]); 
         serializer.endTag(null, "CorrectAnswer"); 

         serializer.startTag(null, "UserAnswer"); 
         serializer.text(uans[i]); 
         serializer.endTag(null, "UserAnswer"); 

        i=i+1; 
        } 

       serializer.endTag(null, "Worksheet"); 
       serializer.endDocument(); 
       //write xml data into the FileOutputStream 
       serializer.flush(); 
       //finally we close the file stream 
       fileos.close(); 

       TextView tv = (TextView)this.findViewById(R.id.result); 
       tv.setText("file has been created on SD card"); 
      } catch (Exception e) { 
       Log.e("Exception","error occurred while creating xml file"); 
      } 
     } 
     public void onClick(View v) 
     { 
      if(v==b3) 
      { 
       // if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){ 
         Thread thread=new Thread(new Runnable(){ 
          public void run(){ 
           doFileUpload(); 
           runOnUiThread(new Runnable(){ 
            public void run() { 
             tv.setText("uploaded successfully"); 
            } 
           }); 
          } 
        }); 
        thread.start(); 
      } 
      } 
     private void doFileUpload(){ 

      File file1 = new File("/mnt/sdcard/"+filename); 
      File file2 = new File("/mnt/sdcard/mfqsheet.xml"); 
      String urlString = "http://192.168.1.20:8080/NpTest/fileUpload"; 
      try 
      { 
       HttpClient client = new DefaultHttpClient(); 
       HttpPost post = new HttpPost(urlString); 
       FileBody bin1 = new FileBody(file1); 
       FileBody bin2 = new FileBody(file2); 
       MultipartEntity reqEntity = new MultipartEntity(); 
       reqEntity.addPart("uploadedfile1", bin1); 
       reqEntity.addPart("uploadedfile2", bin2); 
       reqEntity.addPart("user", new StringBody("User")); 
       post.setEntity(reqEntity); 
       HttpResponse response = client.execute(post); 
       resEntity = response.getEntity(); 
       final String response_str = EntityUtils.toString(resEntity); 
       if (resEntity != null) { 
        Log.i("RESPONSE",response_str); 
        runOnUiThread(new Runnable(){ 
          public void run() { 
           try { 

            // Toast.makeText(getApplicationContext(),"Upload <span id="IL_AD4" class="IL_AD">Complete</span>. Check the server uploads directory.", Toast.LENGTH_LONG).show(); 
           } catch (Exception e) { 
            e.printStackTrace(); 
           } 
           } 
         }); 
       } 
      } 
      catch (Exception ex){ 
       Log.e("Debug", "error: " + ex.getMessage(), ex); 
      } 
      } 
    } 
+0

你有服務器端代碼嗎?即Web服務的代碼?我需要一個樣本前綴。在.NET中。你可以發佈一個樣本嗎?謝謝.. – beerBear

相關問題