在Android中调用.NET Web服务

8

我使用.NET web服务返回XML。当我在Android上使用ksoap2调用web服务时,出现了这个问题。

请帮忙解决。

Eclipse中的Logcat:

12-19 15:58:11.951: W/dalvikvm(2041): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
12-19 15:58:11.961: E/AndroidRuntime(2041): FATAL EXCEPTION: main
12-19 15:58:11.961: E/AndroidRuntime(2041): java.lang.RuntimeException: double ID
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:407)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.readUnknown(SoapSerializationEnvelope.java:273)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:389)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.readUnknown(SoapSerializationEnvelope.java:273)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:389)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.readUnknown(SoapSerializationEnvelope.java:273)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.read(SoapSerializationEnvelope.java:389)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.serialization.SoapSerializationEnvelope.parseBody(SoapSerializationEnvelope.java:151)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.SoapEnvelope.parse(SoapEnvelope.java:140)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.transport.Transport.parseResponse(Transport.java:116)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:259)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:114)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at com.example.webservicee.MainActivity$1.onClick(MainActivity.java:133)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.view.View.performClick(View.java:2408)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.view.View$PerformClick.run(View.java:8816)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.os.Handler.handleCallback(Handler.java:587)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.os.Looper.loop(Looper.java:123)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at android.app.ActivityThread.main(ActivityThread.java:4627)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at java.lang.reflect.Method.invokeNative(Native Method)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at java.lang.reflect.Method.invoke(Method.java:521)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-19 15:58:11.961: E/AndroidRuntime(2041):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

MainActivity.java

package com.example.webservicee; 
import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
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.xmlpull.v1.XmlPullParserException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    final static String NAMESPACE = "http://tempuri.org/";

    final static String METHOD_NAME = "GetContent";

    final static String SOAP_ACTION = "http://tempuri.org/GetContent";

    final static String URL = "http://www.example.com/XMLGenerator/GenerateXML.asmx";


    private Button Mybtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        deger = (EditText) findViewById(R.id.deger);
        sonuc = (TextView) findViewById(R.id.flag);
        Mybtn = (Button) findViewById(R.id.hesapla);
        Mybtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);

                //My webservice paramaters 
                Request.addProperty("SectionsInclude","10");
                Request.addProperty("DocumentCount",10);
                Request.addProperty("SortBy","0");
                Request.addProperty("SortOrder","ASC");
                Request.addProperty("UserName","myuser");
                Request.addProperty("Pass","Lsss");
                /**/
                      /*  PropertyInfo pi=new PropertyInfo();
                        pi.setName("arg0");
                        pi.setValue("10");
                        pi.setType(String.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();


                        pi.setName("arg1");
                        pi.setValue(10);
                        pi.setType(Integer.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();


                        pi.setName("arg2");
                        pi.setValue("0");
                        pi.setType(String.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();


                        pi.setName("arg3");
                        pi.setValue("ASC");
                        pi.setType(String.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();

                        pi.setName("arg4");
                        pi.setValue("myuser");
                        pi.setType(String.class);
                        Request.addProperty(pi);
                        pi=new PropertyInfo();


                        pi.setName("arg5");
                        pi.setValue("Lsss");
                        pi.setType(String.class);
                        Request.addProperty(pi);


                        */


                SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                soapEnvelope.dotNet = true;
                soapEnvelope.setOutputSoapObject(Request);
                //soapEnvelope.bodyOut = Request;
                HttpTransportSE aht = new HttpTransportSE(URL);
                try {
                    aht.call(SOAP_ACTION, soapEnvelope);


                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String result;
                try {

                    result = "Fahrenheit:"+(SoapPrimitive) soapEnvelope.getResponse();
                     Log.d("--Result-- ", result);
                    //sonuc.setText(result);

                    } catch (SoapFault e) 
                    {

                    e.printStackTrace();

                    }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

这是示例响应XML:

以下是示例响应XML:

<?xml version="1.0" encoding="utf-8"?>
<liste>
<document id="6" titles="bestPeople" showingDate="27.09.2011 00:00:00"  date="27.09.2011 00:00:00" ContentID=rbHe8zKvDTG7TLS" >
<part id="6" baslik="best" icerik="&lt;table style=&quot;width: 188px; height: 24px;&quot; border=&quot;tbody&gt;&#xD;&#xA;&lt;/table&gt;" resim="">
<SecNotes><![CDATA[]]></SecNotes>
<ContNotes><![CDATA[]]></ContNotes>
</part>
<SecNotes><![CDATA[]]></SecNotes>
<ContNotes><![CDATA[]]></ContNotes>
</document>
</liste>

由于调用堆栈显示正在执行 HttpTransportSE.call, 我猜测您代码中的位置在 aht.call(...) 之后或者之中。由于调用堆栈还显示 SoapEnvelope.parseaht.call(...) 显然没有返回,因此问题似乎在您 Web 服务的响应中。 - prprcupofcoffee
1
嗨Erham,你的WS已经发布了吗?我认为你的代码不是问题所在。 - Jorgesys
嗨@Jorgesys,这是我的方法。谢谢。http://www.muhabbetsokaklari.com/LEdisXMLGenerator/GenerateXML.asmx?op=GetContentTreeBySections - Erhan Demirci
我看到你需要用户名/密码,你能发一个响应的例子吗? - Jorgesys
3个回答

4
我解决了这个问题。我添加了以下代码,现在它可以正常工作。 我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
}
private void init()
{
    //your webservice envelope
    String envelope="<?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><GetContentTreeBySections xmlns=\"http://tempuri.org/\"><SectionsInclude>%s</SectionsInclude><DocumentCount>%s</DocumentCount><SortBy>%s</SortBy><SortOrder>%s</SortOrder><UserName>%s</UserName><Pass>%s</Pass></GetContentTreeBySections></soap:Body></soap:Envelope>";

    String myEnvelope = String.format(envelope, "myParam1 value", "myParam2 value","myParam3 value","myParam4 value");
    String url = "http://www.mywebserice.com/XMLGenerator/GenerateXML.asmx";
    String soapAction = "http://tempuri.org/GetContentTreeBySections"; 
    String response = CallWebService(url, soapAction, myEnvelope);
    //Log.v("response", response);
    Toast.makeText(getApplicationContext(), "this"+response,Toast.LENGTH_LONG).show();
    String xml=response;    
}

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
String CallWebService(String url,String soapAction,String envelope) 
{

      final DefaultHttpClient httpClient=new DefaultHttpClient();
      // request parameters
      HttpParams params = httpClient.getParams();
         HttpConnectionParams.setConnectionTimeout(params, 10000);
         HttpConnectionParams.setSoTimeout(params, 15000);
         // set parameter
      HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

      // POST the envelope
      HttpPost httppost = new HttpPost(url);
      // add headers
         httppost.setHeader("soapaction", soapAction);
         httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
         String responseString="";

         try 
         {
                // the entity holds the request
                HttpEntity entity = new StringEntity(envelope);
                httppost.setEntity(entity);

                // Response handler
                ResponseHandler<String> rh=new ResponseHandler<String>() {
        // invoked when client receives response
        public String handleResponse(HttpResponse response)
          throws ClientProtocolException, IOException {

         // get response entity
         HttpEntity entity = response.getEntity();

         // read the response as byte array
               StringBuffer out = new StringBuffer();
               byte[] b = EntityUtils.toByteArray(entity);

               // write the response byte array to a string buffer
               out.append(new String(b, 0, b.length));
               return out.toString();
        }
       };

       responseString=httpClient.execute(httppost, rh); 

      }
         catch (Exception e) {
          Log.v("exception", e.toString());
      }

         // close the connection
      httpClient.getConnectionManager().shutdown();
      return responseString;
}

3
如果您说出您添加或更改的内容,使其起作用,那么您的回答将更有用。 - rds
@rds 我尝试了很多关于我的 Web 服务的教程,但都没有成功,后来我尝试了这段代码,它可以工作。此外,ksoap2 对于我的 Web 服务也不起作用。谢谢。 - Erhan Demirci

2

不要使用ksoap,尝试使用开源的ice-soap库。它比ksoap更好,提供了使用注释发送请求和解析响应的高效库。


1
首先,永远不要在主线程中使用网络操作,尝试将网络操作插入非主线程中,例如AsyncTask或任何其他工作线程。 其次,使用以下代码获取结果:
 String message="";
    SoapObject result = (SoapObject)envelope.bodyIn;
    if(result != null)
       {
          message=result.getProperty(0).toString();
       }

并且更改以下代码

Request.addProperty("DocumentCount",10);

待定

Request.addProperty("DocumentCount","10");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接