2012-08-05 65 views
4

我想将它作为XML发送到我的Web服务。我应该怎么做?将XML发送到Android中的Web服务

<dmi:ShipNoticeRequest xmlns:dmi="http://portal.suppliesnet.net"> 
<dmi:RequesterISA>xxxxxxxxxx</dmi:RequesterISA> 
<dmi:ShipDateRange> 
<dmi:ShipDateFrom>2009-09-09</dmi: ShipDateFrom> 
<dmi:ShipDateTo>2009-09-10</dmi: ShipDateTo> 
</dmi: ShipDateRange > 
</dmi:ShipNoticeRequest> 

我的Web服务方法需要这种类型的请求消息:

POST /ShipNotice/WebServiceShipNotice.asmx HTTP/1.1 
Host: portal.suppliesnet.net 
Content-Type: text/xml; charset=utf-8 
Content-Length: length 
SOAPAction: "http://portal.suppliesnet.net/RequestShipmentNoticeXML" 

<?xml version="1.0" encoding="utf-8"?> 
<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:Body> 
    <RequestShipmentNoticeXML xmlns="http://portal.suppliesnet.net"> 
     <ShipNoticeRequestNode>xml</ShipNoticeRequestNode> 
    </RequestShipmentNoticeXML> 
    </soap:Body> 
</soap:Envelope> 

我特林这种方法,但你能弄清楚什么是错这个代码geeting未知错误?

try { 
      DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory 
        .newInstance(); 
      DocumentBuilder documentBuilder = documentBuilderFactory 
        .newDocumentBuilder(); 
      Document document = documentBuilder.newDocument(); 
      Element rootElement = document.createElement("soap:Envelope"); 
      rootElement.setAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance"); 
      rootElement.setAttribute("xmlns:xsd","http://www.w3.org/2001/XMLSchema"); 
      rootElement.setAttribute("xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/"); 


      document.appendChild(rootElement); 

      Element SoapBody = document.createElement("soap:Body"); 
      rootElement.appendChild(SoapBody); 

      Element RequestShipmentNoticeXML = document.createElement("RequestShipmentNoticeXML"); 
      RequestShipmentNoticeXML.setAttribute("xmlns","http://portal.suppliesnet.net"); 
      SoapBody.appendChild(RequestShipmentNoticeXML); 

      Element ShipmentNoticeRequestNode = document.createElement("ShipNoticeRequestNode"); 
      RequestShipmentNoticeXML.appendChild(ShipmentNoticeRequestNode); 

      Element shipNoticeRequest = document.createElement("dmi:ShipNoticeRequest"); 
      shipNoticeRequest.setAttribute("xmlns:dmi", "http://portal.suppliesnet.net"); 

      ShipmentNoticeRequestNode.appendChild(shipNoticeRequest); 

      Element ContactElement = document.createElement("dmi:RequesterISA"); 
      shipNoticeRequest.appendChild(ContactElement); 
      ContactElement.appendChild(document.createTextNode("XXXXXX")); 
// 1969-12-31 


      Element articleElement = document.createElement("dmi:ShipDateRange"); 

      Element ShipDateFrom = document.createElement("dmi:ShipDateFrom"); 
      articleElement.appendChild(ShipDateFrom); 
      ShipDateFrom.appendChild(document.createTextNode("2012-07-06")); 

      Element ShipDateTo = document.createElement("dmi:ShipDateTo"); 
      articleElement.appendChild(ShipDateTo); 
      ShipDateTo.appendChild(document.createTextNode("2012-07-06")); 

      shipNoticeRequest.appendChild(articleElement); 


      TransformerFactory factory = TransformerFactory.newInstance(); 
      Transformer transformer = factory.newTransformer(); 
      Properties outFormat = new Properties(); 

      outFormat.setProperty(OutputKeys.INDENT, "yes"); 
      outFormat.setProperty(OutputKeys.METHOD, "xml"); 
      outFormat.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); 
      outFormat.setProperty(OutputKeys.VERSION, "1.0"); 
      outFormat.setProperty(OutputKeys.ENCODING, "UTF-8"); 
      transformer.setOutputProperties(outFormat); 
      DOMSource domSource = new DOMSource(document.getDocumentElement()); 
      OutputStream output = new ByteArrayOutputStream(); 
      StreamResult result = new StreamResult(output); 
      transformer.transform(domSource, result); 
      xmlString = output.toString(); 

     } catch (ParserConfigurationException e) { 
     } catch (TransformerConfigurationException e) { 
     } catch (TransformerException e) { 
     } 

     SoapObject request = new SoapObject(namespace, methodName); 
     request.addProperty("RequestShipmentNoticeXMl",xmlString); 

     SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
       SoapEnvelope.VER11); 

     envelope.dotNet = true; 
     envelope.setOutputSoapObject(request); 
     // envelope.headerIn. 
     final HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); 

     androidHttpTransport.debug = true; 
     try { 
      androidHttpTransport.call(Soap_Action, envelope); 
      //androidHttpTransport. 
      SoapObject SoapResult = (SoapObject)envelope.bodyIn; 
      tv.setText("Status" + SoapResult); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
      Log.e("static", "Exception in making call to server"); 
     } 
+0

一些问题 - 而不是为你写代码)。 1)现在输出结果是什么样的? 2)。您是否已成功将XML文件发布到该Web服务?在我看来,如果您先从存储在应用程序中的工作文件示例开始,那么您将知道该服务是否接受它。 3)“未知”错误在哪里?从服务器?有没有一种Web服务方法来发回调试消息? – 2012-08-16 19:16:46

+0

是的,它是一个web服务方法,它给我回错误11号和在Web服务的文档中我检查错误11意味着未知的错误。当我调试我的应用程序时,它的运行没有任何异常,当切换点达到接收响应消息我收到这个回应 – Wajeeha 2012-08-17 06:01:54

回答

2

你想发送SOAP消息和Android没有直接支持发送这些类型的消息。有像KSOAP2-android这样的第三方库,你可以试试。
每个SOAP消息应该如何由服务器端的WSDL文件给出。试着在服务器上找到它,看看每个消息应该是什么样子。您可以使用soapUI为您解析WSDL文件。
如果您没有使用上述任何第三方库,您必须自行撰写该消息。您将需要建立某种形式的HTTP客户端这样的:

HttpURLConnection conn = null; 
conn = (HttpURLConnection) new URL(url).openConnection(); 
conn.setRequestMethod("POST"); 
conn.setRequestProperty("Content-Type", "text/xml"); 
conn.setRequestProperty("Content-Length", "" + postMessageInBytes.length); 

机构的请求将使用例如XmlSerializer的创建,这将有助于您编写需要标签等

1

您可以使用KSOAP2访问Web服务和XML数据可以很容易地被作为字符串...

1.Download的ksoap2 jar文件

2.启动Eclipse和创建新的Android项目

3.右键点击你的项目

4.Click性能

5.Click从左侧窗格中

6.Select库选项卡

7.Click上添加Java构建路径外部罐子

8.浏览下载的jar文件

您的活动应该看起来像这样...

import org.ksoap2.SoapEnvelope; 
import org.ksoap2.serialization.SoapObject; 
import org.ksoap2.serialization.SoapPrimitive; 
import org.ksoap2.serialization.SoapSerializationEnvelope; 
import org.ksoap2.transport.HttpTransportSE; 
import android.app.*; 
import android.util.Log; 
import android.widget.TextView; 
import android.os.Bundle; 

public class FinalWebServiceDemoActivity extends Activity { 

// some parameters regarding your web-service to be invoked 
private static final String SOAP_ACTION = "http://tempuri.org/WebServiceMethod"; 
private static final String METHOD_NAME = "WebServiceMethod"; 
private static final String NAMESPACE = "http://tempuri.org/"; 
private static final String URL = "http://10.0.2.2:2256/WebService.asmx"; 

TextView tv; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    tv=(TextView)findViewById(R.id.text1); 
    call(); 
} 

public void call() 
{ 
    try { 
     SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
     request.addProperty("message","Put your XML data here..."); 

     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 strRes = result.toString(); 

     tv.setText(strRes); 
    } catch (Exception e) { 
     tv.setText("Exception..."); 
     Log.i("exception", e.toString()); 
     StackTraceElement elements[] = e.getStackTrace(); 
     for (int i = 0, n = elements.length; i < n; i++) {  
      Log.i("File", elements[i].getFileName()); 
      Log.i("Line", String.valueOf(elements[i].getLineNumber())); 
      Log.i("Method", elements[i].getMethodName()); 
     } 
    } 
} 
} 

不要忘记在清单文件中添加<uses-permission android:name="android.permission.INTERNET" />权限。

注意:此代码是为了访问在本地计算机上运行的.NET Web服务而编写的,而要访问的是Android模拟器。必要时修改它。

希望这有助于...

+0

我想用这种方式,但得到一个未知的错误。你可以弄清楚这段代码有什么问题; – Wajeeha 2012-08-16 05:40:38

+0

请在这里粘贴具体的错误说明请... – 2012-08-16 06:23:16

+0

没有例外,但有我的web服务中定义的错误消息,我得到的响应是“statusRequestShipmentNoticeXMLResponse {RequestShipmetNoticeXMLResult {errorNumber = 11} Error Description = Unknown error”(object refrence没有设置为对象的实例) – Wajeeha 2012-08-16 07:16:19

1

试试这个(纯Java标准):

 private WebServiceConnection(String xmlString) { 

     InputStream responseInputStream = null; 
     OutputStream requestOutputStream = null; 

     HttpURLConnection httpURLConnection = null; 

     try { 

      // Form the URL 
      URL url = new URL(URL_BASE + "?serviceId=3"); 

      // Set the HTTP URL connection 
      httpURLConnection = (HttpURLConnection)url.openConnection(); 
      httpURLConnection.setDoOutput(true); 
      httpURLConnection.setConnectTimeout(15000); 
      httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8"); 
      httpURLConnection.setRequestProperty("Content-Type", "text/html"); 

      // Send request 
      requestOutputStream = httpURLConnection.getOutputStream(); 
      requestOutputStream.write(xmlString.getBytes("UTF-8")); 

      // Receive response, then do anything with it 
      responseInputStream = httpURLConnection.getInputStream(); 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch(SocketTimeoutException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
0
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[] { 
        "type1", 
        "type2", 
        "type3", 
        "type4", 
        "type5",  
       }; 
      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 "addupload.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); 
     } 
     } 
}