开发者

How To Send the xml file to .net web service in android

I want to send the xml file to .net web service but it did not work. In my project i have created xml file by using DOM Object. I want to send that Dom object to the server but It doent work.

I also used Ksoap2 jar file in my project. Please help me how to send the xml file to .net server. Here is my code:

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开发者_JAVA技巧.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());
            }


        }
}


I suggest you to write a data class and deserialize your XML file into an instance of it. (JAXB automates that process but as far as I know you cannot use JAXB with Android. So you need to write your own parser.) Then pass that object to your .NET web service, and serialize it again to XML on the server side with .NET XMLSerializer. You can pass your custom classes with k-soap2 when calling .NET web or WCF services.

For example you have an XML file like the following: <person> <name>xyz</name> <surname>abc</surname> <age>30</age> </person> Create a Person class both on the server side and the client side with name, surname and age attributes. Then parse your xml file to an instance of your Person class on the client side. Now you can send your Person instance to your Web Service. In this case of course you need to edit your web service so it can accept your type (in this example Person).

If you have further problems let me know.


**

code for upload dynamically created xml from sdcard to weservice in android:

**

    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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜