android - 如何在android中使用kso​​ap解析调用方法时发送参数

标签 android android-intent ksoap2

我正在做基于 soap 的解析。当方法中没有参数时,我能够得到响应。但是现在我正在调用具有一些参数并返回对象的函数。在尝试时我得到了 null。我正在调用此函数 getDestinationStationDashboard 且参数为 "HNH"

这是我的代码。

package com.example.soapbased;

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.AndroidHttpTransport;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class Soapclass extends Activity {
    private static final String SOAP_ACTION = "http://wsendpoints.bbrailapps.firstgroup.com/getDestinationStationDashboard";
    private static final String METHOD_NAME = "getDestinationStationDashboard";
    private static final String NAMESPACE = "http://wsendpoints.bbrailapps.firstgroup.com";
    private static final String URL = "http://railapps.firstgroup.com/FirstGroupRailApps/services/RailAppsCAWS?wsdl";
    private SoapObject resultRequestSOAP = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_soapclass);
        System.out.println("=====================" + haveNetworkConnection());

        new AsyncTask<Void, Void, Object>() {
            ProgressDialog dialog = new ProgressDialog(Soapclass.this);
            private PropertyInfo pi1;

            protected void onPreExecute() {
                dialog.show();
            };

            protected Object doInBackground(Void[] params) {

                /*resultRequestSOAP = new SoapObject(NAMESPACE, METHOD_NAME);

                SoapSerializationEnvelope envp = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                envp.dotNet = true;
                envp.setOutputSoapObject(resultRequestSOAP);
                AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
                        URL);
                try {
                    androidHttpTransport.call(SOAP_ACTION, envp);
                    SoapPrimitive resultsString = (SoapPrimitive)envp.getResponse();
                    System.out.println("resultsString"+resultsString);
                    return resultsString.toString();

                } catch (Exception e) {
 System.out.println("---------------------------"+e.toString());
 Log.d("ppp", e.toString());
                    Toast.makeText(Soapclass.this,
                            "Check Network connectivety" + e.toString(),
                            Toast.LENGTH_LONG).show();
                    Log.v("WS Error->", e.toString());
                    return e.toString();
                }*/

                 resultRequestSOAP = new SoapObject(NAMESPACE, METHOD_NAME);
                 pi1 = new PropertyInfo();
                 pi1.setName("crsCode");
                 pi1.setValue("HNH");//get the string that is to be sent to the web service
                 pi1.setType(String.class);
                 resultRequestSOAP.addProperty(pi1);
                SoapSerializationEnvelope envp = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                envp.dotNet = true;
                envp.setOutputSoapObject(resultRequestSOAP);
                AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
                        URL);
                try {
                    androidHttpTransport.call(SOAP_ACTION, envp);
                    SoapPrimitive resultsString = (SoapPrimitive)envp.getResponse();
                    System.out.println("resultsString"+resultsString);
                    return resultsString;

                } catch (Exception e) {
 System.out.println("---------------------------"+e.toString());
 Log.d("ppp", e.toString());
                    Toast.makeText(Soapclass.this,
                            "Check Network connectivety" + e.toString(),
                            Toast.LENGTH_LONG).show();
                    Log.v("WS Error->", e.toString());
                    return e.toString();
                }


            };

            protected void onPostExecute(String result) {
                dialog.dismiss();
                Toast.makeText(Soapclass.this,
                        "Check Network connectivety" + result,
                       Toast.LENGTH_LONG).show();
            };
        }.execute();

    }

    public boolean haveNetworkConnection() {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;
    }

}

更改后我得到这个对象 我得到这个 SoapObject obj = (SoapObject)envp.getResponse(); System.out.println("resultsString"+obj);

resultsStringanyType{RID=201309201377618; alertDetailPopulated=true; alertsId=0; alertsSummary=anyType{}; destExpArrival=06:31; destSchArrival=06:30; destinationStation=anyType{crsCode=BKJ; stationName=Beckenham Junction; }; expArrival=06:19; expDepart=06:20; otherAlertPresent=false; platformNo=3; routeDetailPopulated=false; routeDetails=null; rsID=null; schArrival=06:19; schDepart=06:19; serviceAlertPresent=false; toc=SE; tocName=Southeastern; trainID=2M06; trainLastReportedAt=null; }

现在如何从该对象打印 RID 或其他内容。

最佳答案

public class MainActivity extends Activity {
    private static final String SOAP_ACTION = "http://wsendpoints.bbrailapps.firstgroup.com/getDestinationStationDashboard";
    private static final String METHOD_NAME = "getDestinationStationDashboard";
    private static final String NAMESPACE = "http://wsendpoints.bbrailapps.firstgroup.com";
    private static final String API_URL = "http://railapps.firstgroup.com/FirstGroupRailApps/services/RailAppsCAWS?wsdl";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new DownloadSoap().execute();
    }

    private void doNetwork() {
        SoapObject resultRequestSOAP = new SoapObject(NAMESPACE, METHOD_NAME);
        PropertyInfo pi1 = new PropertyInfo();
        pi1.setName("crsCode");
        pi1.setValue("HNH");
        pi1.setType(PropertyInfo.STRING_CLASS);
        resultRequestSOAP.addProperty(pi1);
        SoapSerializationEnvelope envp = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envp.dotNet = true;
        try {
            envp.setOutputSoapObject(resultRequestSOAP);
            HttpTransportSE androidHttpTransport = new HttpTransportSE(API_URL);
            androidHttpTransport.debug = true;
            androidHttpTransport.call(SOAP_ACTION, envp);
            System.out.println(androidHttpTransport.requestDump);
            System.out.println(androidHttpTransport.responseDump);
            SoapObject response = (SoapObject) envp.getResponse();
            System.out.println("resultsString" + response.toString());

        } catch (Exception e) {

        }

    }

    @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;
    }

    public class DownloadSoap extends AsyncTask<Void, Void, Void> {
        private ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(MainActivity.this);
            pd.setMessage("Fetching Data");
            pd.setIndeterminate(true);
            pd.setCancelable(false);
            pd.show();
        }
        @Override
        protected Void doInBackground(Void... params) {
            doNetwork();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            pd.dismiss();
        }
    }

}

它对我有用,但是获取数据要花很多时间。

我收到如下响应:-

09-20 12:22:39.974: I/System.out(2421): <?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><getDestinationStationDashboardResponse 
xmlns="http://wsendpoints.bbrailapps.firstgroup.com"><getDestinationStationDashboardReturn><RID>201309201377851</RID><alertDetailPopulated>false</alertDetailPopulated>
<alertsId>0</alertsId><alertsSummary xsi:nil="true"/><destExpArrival>08:15</destExpArrival><destSchArrival>08:15</destSchArrival><destinationStation><crsCode>BKJ</crsCode>
<stationName>Beckenham Junction</stationName></destinationStation><expArrival>08:04</expArrival><expDepart>08:04</expDepart><otherAlertPresent>false</otherAlertPresent>
<platformNo>3</platformNo><routeDetailPopulated>false</routeDetailPopulated><routeDetails xsi:nil="true"/><rsID xsi:nil="true"/><schArrival>08:04</schArrival><schDepart>08:04</schDepart>
<serviceAlertPresent>false</serviceAlertPresent><toc>SE</toc><tocName>Southeastern</tocName><trainID>2M20</trainID><trainLastReportedAt xsi:nil="true"/></getDestinationStationDashboardReturn>
<getDestinationStationDashboardReturn><RID>201309201377886</RID><alertDetailPopulated>false</alertDetailPopulated><alertsId>0</alertsId><alertsSummary xsi:nil="true"/>
<destExpArrival>08:30</destExpArrival><destSchArrival>08:30</destSchArrival><destinationStation><crsCode>BKJ</crsCode><stationName>Beckenham Junction</stationName>
</destinationStation><expArrival>08:19</expArrival><expDepart>08:19</expDepart><otherAlertPresent>false</otherAlertPresent><platformNo>3</platformNo>
<routeDetailPopulated>false</routeDetailPopulated><routeDetails xsi:nil="true"/><rsID xsi:nil="true"/><schArrival>08:19</schArrival><schDepart>08:19</schDepart>
<serviceAlertPresent>false</serviceAlertPresent><toc>SE</toc><tocName>Southeastern</tocName><trainID>2M22</trainID><trainLastReportedAt xsi:nil="true"/>
</getDestinationStationDashboardReturn><getDestinationStationDashboardReturn><RID>201309201377085</RID><alertDetailPopulated>false</alertDetailPopulated>
<alertsId>0</alertsId><alertsSummary xsi:nil="true"/><destExpArrival>09:38</destExpArrival><destSchArrival>09:38</destSchArrival><destinationStation>
<crsCode>BDM</crsCode><stationName>Bedford</stationName></destinationStation><expArrival>08:12</expArrival><expDepart>08:13</expDepart>
<otherAlertPresent>false</otherAlertPresent><platformNo>2</platformNo><routeDetailPopulated>false</routeDetailPopulated><routeDetails xsi:nil="true"/>
<rsID xsi:nil="true"/><schArrival>08:12</schArrival><schDepart>08:13</schDepart><serviceAlertPresent>false</serviceAlertPresent>
<toc>SE</toc><tocName>Southeastern</tocName><trainID>1G65</trainID><trainLastReportedAt xsi:nil="true"/></getDestinationStationDashboardReturn>
<getDestinationStationDashboardReturn><RID>201309201386846</RID><alertDetailPopulated>false</alertDetailPopulated><alertsId>0</alertsId>
<alertsSummary xsi:nil="true"/><destExpArrival>10:08</destExpArrival><destSchArrival>10:08</destSchArrival><destinationStation>
<crsCode>BDM</crsCode><stationName>Bedford</stationName></destinationStation><expArrival>08:41</expArrival>
<expDepart>08:41</expDepart><otherAlertPresent>false</otherAlertPresent><platformNo>1</platformNo>
<routeDetailPopulated>false</routeDetailPopulated><routeDetails xsi:nil="true"/><rsID xsi:nil="true"/>
<schArrival>08:41</schArrival><schDepart>08:41</schDepart><serviceAlertPresent>false</serviceAlertPresent>
<toc>FC</toc><tocName>First Capital Connect</tocName><trainID>2W70</trainID><trainLastReportedAt>Train last reported at : Haywards Heath</trainLastReportedAt>
</getDestinationStationDashboardReturn><getDestinationStationDashboardReturn><RID>201309201377851</RID><alertDetailPopulated>false</alertDetailPopulated>
<alertsId>0</alertsId><alertsSummary xsi:nil="true"/><destExpArrival>08:24</destExpArrival><destSchArrival>08:24</destSchArrival><destinationStation>
<crsCode>BKL</crsCode><stationName>Bickley</stationName></destinationStation><expArrival>08:04</expArrival><expDepart>08:04</exp

希望对您有所帮助。


使用此类帮助解析 Soap Response 的最简单方法 创建类名SoapResponseParser

public class SoapResponseParser {


    public static void parseBusinessObject(String input, Object output)
            throws NumberFormatException, IllegalArgumentException,
            IllegalAccessException, InstantiationException {

        @SuppressWarnings("rawtypes")
        Class theClass = output.getClass();
        Field[] fields = theClass.getDeclaredFields();

        for (int i = 0; i < fields.length; i++) {
            Type type = fields[i].getType();
            fields[i].setAccessible(true);

            // detect String
            if (fields[i].getType().equals(String.class)) {
                String tag = fields[i].getName() + "=";

                if (input.contains(tag)) {
                    String strValue = input.substring(
                            input.indexOf(tag) + tag.length(),
                            input.indexOf(";", input.indexOf(tag)));
                    if (strValue.length() != 0) {
                        if (strValue.contains("anyType")) {
                            fields[i].set(output, "-");
                        } else
                            fields[i].set(output, strValue);
                    }
                }
            }

            // detect int or Integer
            if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
                String tag = fields[i].getName() + "=";

                if (input.contains(tag)) {
                    String strValue = input.substring(
                            input.indexOf(tag) + tag.length(),
                            input.indexOf(";", input.indexOf(tag)));
                    if (strValue.length() != 0) {
                        fields[i].setInt(output, Integer.valueOf(strValue));
                    }
                }
            }

            // detect float or Float
            if (type.equals(Float.TYPE) || type.equals(Float.class)) {
                String tag = fields[i].getName() + "=";
                if (input.contains(tag)) {
                    String strValue = input.substring(
                            input.indexOf(tag) + tag.length(),
                            input.indexOf(";", input.indexOf(tag)));
                    if (strValue.length() != 0) {
                        fields[i].setFloat(output, Float.valueOf(strValue));
                    }
                }
            }
            // detect double or Double
            if (type.equals(Double.TYPE) || type.equals(Double.class)) {
                String tag = fields[i].getName() + "=";
                if (input.contains(tag)) {
                    String strValue = input.substring(
                            input.indexOf(tag) + tag.length(),
                            input.indexOf(";", input.indexOf(tag)));
                    if (strValue.length() != 0) {
                        fields[i].setDouble(output, Double.valueOf(strValue));
                    }
                }
            }
         }      
      }
}

编辑的 doNetwork() 方法

private void doNetwork() {
        SoapObject resultRequestSOAP = new SoapObject(NAMESPACE, METHOD_NAME);
        PropertyInfo pi1 = new PropertyInfo();
        pi1.setName("crsCode");
        pi1.setValue("HNH");
        pi1.setType(PropertyInfo.STRING_CLASS);
        resultRequestSOAP.addProperty(pi1);
        SoapSerializationEnvelope envp = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envp.dotNet = true;
        try {
            envp.setOutputSoapObject(resultRequestSOAP);
            HttpTransportSE androidHttpTransport = new HttpTransportSE(API_URL);
            androidHttpTransport.debug = true;
            androidHttpTransport.call(SOAP_ACTION, envp);
            System.out.println(androidHttpTransport.requestDump);
            System.out.println(androidHttpTransport.responseDump);
            SoapObject response = (SoapObject) envp.getResponse();
            GetDestinationStationDashboardReturn destination= new GetDestinationStationDashboardReturn();
            System.out.println("resultsString" + response.toString());
            SoapResponseParser.parseBusinessObject(response.toString(),
                    destination);
            System.out.println(destination.getRID()+"  "+destination.getAlertDetailPopulated()+" "+destination.getAlertsId());

        } catch (Exception e) {

        }

    }

现在我解释了如何解析,现在由您决定如何实现您的要求。 快乐编码。


创建一个类 GetDestinationStationDashboardReturn

public class GetDestinationStationDashboardReturn {
    private String RID;
    private String alertDetailPopulated;
    private String alertsId;
    private String destExpArrival;
    private String destSchArrival;
    public String getRID() {
        return RID;
    }
    public void setRID(String rID) {
        RID = rID;
    }
    public String getAlertDetailPopulated() {
        return alertDetailPopulated;
    }
    public void setAlertDetailPopulated(String alertDetailPopulated) {
        this.alertDetailPopulated = alertDetailPopulated;
    }
    public String getAlertsId() {
        return alertsId;
    }
    public void setAlertsId(String alertsId) {
        this.alertsId = alertsId;
    }
    public String getDestExpArrival() {
        return destExpArrival;
    }
    public void setDestExpArrival(String destExpArrival) {
        this.destExpArrival = destExpArrival;
    }
    public String getDestSchArrival() {
        return destSchArrival;
    }
    public void setDestSchArrival(String destSchArrival) {
        this.destSchArrival = destSchArrival;
    }

}

关于android - 如何在android中使用kso​​ap解析调用方法时发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18908831/

相关文章:

android.widget.Button 无法转换为 android.widget.EditText

android - QR 扫描仪相机预览停止并再次启动,然后在读取二维码时关闭

android - ZXing如何扫描二维码和一维条码?

android - 当一个 parcelable 对象通过一个 intent 传递时,它会更新对原始对象的引用吗?

java - 当我使用 Intent 传递序列化对象状态时如何保存它

android - 在模拟器中使用 kSOAP2 使用本地主机 WCF 服务

java - 用@Override注解继承的方法是不是必须的?

java - Android 评级栏显示额外的剩余部分

parameters - 如何确定 wsdl Web 服务中的方法名称和参数

android - KSOAP 为节点添加自定义类型