在android

时间:2017-03-29 08:38:22

标签: java android xml web-services android-ksoap2

我需要在Android设备中调用soap webservice。我一直在阅读stackoverflow和其他页面上的很多文章,观看视频......但是我已经尝试了所有的东西而且我无法在我的Android设备中使它工作,我无法做到在模拟器上测试,因为我的计算机无法处理它们中的任何一个,因此我不知道错误是否在代码上或者是否是我的Android设备的问题。

布局xml只是EditText,Button和TextView。

在此链接中,您可以看到我需要发送到Web服务的请求xml(我应该使用SOAP 1.1还是SOAP 1.2?) http://www.webservicex.net/globalweather.asmx?op=GetCitiesByCountry

这是我的实际代码,我尝试了许多其他方法,但没有一个方法适合我。有帮助吗? (url,namespace,soap_action和method_name值是okey,不是吗?)

package com.example.doazdoas.webservice_prueba;


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

    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;

    import android.os.AsyncTask;
    import android.widget.Toast;

    import static android.content.ContentValues.TAG;

   public class MainActivity extends Activity{
    private TextView textResult;
    private Button buttonSend;

    String NAMESPACE = "http://www.webserviceX.NET/";
    String METHOD_NAME = "GetCitiesByCountry";
    String SOAP_ACTION = NAMESPACE + METHOD_NAME;
    String URL = "http://www.webservicex.net/globalweather.asmx?WSDL";

    private Object resultsRequestSOAP = null;

    HttpTransportSE androidHttpTransport;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textResult = (TextView)findViewById(R.id.textResultado);
        buttonSend = (Button)findViewById(R.id.buttonEnviar);
        //setContentView(tv);
    }

    public void onClickEnviar(View view){
        AsyncCallWS task = new AsyncCallWS();
        task.execute();
    }

    private class AsyncCallWS extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute");
        }

        @Override
        protected Void doInBackground(Void... params) {
            Log.i(TAG, "doInBackground");
            sendRequest();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Log.i(TAG, "onPostExecute");
            Log.d("dump Request: " ,androidHttpTransport.requestDump);
            Log.d("dump response: " ,androidHttpTransport.responseDump);
        }

    }


    public void sendRequest(){
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);


        //SoapObject
        request.addProperty("@CountryName", "SPAIN");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);


        androidHttpTransport = new HttpTransportSE(URL);
        try
        {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            resultsRequestSOAP =  envelope.getResponse();
            String[] results = (String[])  resultsRequestSOAP;
            textResult.setText( results[0]);
        }
        catch (Exception aE)
        {
            aE.printStackTrace ();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您可以在doInBackGround中执行任何与UI相关的操作,因此请将其移至onPostExecute methnod。

因为doInBackGround不是UI线程。请仔细阅读AsyncTask文档。无论您从doInBackGround返回的数据是什么,它都会被视为onPostExecute的输入。

所以改变你的代码如下,

    private class AsyncCallWS extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        Log.i(TAG, "onPreExecute");
    }

    @Override
    protected String[] doInBackground(Void... params) {
        Log.i(TAG, "doInBackground");
        String[] data = sendRequest();
        return data;
    }

    @Override
    protected void onPostExecute(String[] result) {
        Log.i(TAG, "onPostExecute");
        if(result != null && result.length > 0){
             textResult.setText( results[0]);
        }
    }

}


private String[] sendRequest(){
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);


    //SoapObject
    request.addProperty("@CountryName", "SPAIN");
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);


    androidHttpTransport = new HttpTransportSE(URL);
    try
    {
        androidHttpTransport.call(SOAP_ACTION, envelope);
        resultsRequestSOAP =  envelope.getResponse();
        String[] results = (String[])  resultsRequestSOAP;
    }
    catch (Exception aE)
    {
        aE.printStackTrace ();
    }
}

答案 1 :(得分:0)

您是否考虑过不使用图书馆来提出肥皂请求?我之前遇到了同样的问题,这让我发现库会让你的工作更难,特别是在改变请求的结构时。这是您在不使用库的情况下发出soap请求的方法: 首先,您需要知道如何使用SOAP Ui这是一个Windows应用程序。您可以在此处导入您的wsdl文件,如果它的语法正确,那么您将看到一个显示Web服务请求正文的屏幕。您可以输入测试值,您将获得响应结构。此链接将指导您如何使用soap ui https://www.soapui.org/soap-and-wsdl/working-with-wsdls.html

现在开始使用android代码:

我们将创建一个名为runTask的类,它扩展异步任务并使用http发送请求主体并获取请求响应:

 private class runTask extends AsyncTask<String, String, String> {

        private String response;
        String string = "your string parameter"
        String SOAP_ACTION = "your soap action here";

        String stringUrl = "http://your_url_here";
        //if you experience a problem with url remove the '?wsdl' ending



        @Override
        protected String doInBackground(String... params) {

            try {

                        //paste your request structure here as the String body(copy it exactly as it is in soap ui)
                        //assuming that this is your request body


                String body = "<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>"+
                                "<GetCitiesByCountryResponse xmlns="http://www.webserviceX.NET">"+
                                "<GetCitiesByCountryResult>"+string+"</GetCitiesByCountryResult>"+
                                "</GetCitiesByCountryResponse>"+
                                "</soap:Body>"+
                                "</soap:Envelope>";


                try {
                    URL url = new URL(stringUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDefaultUseCaches(false);
                    conn.setRequestProperty("Accept", "text/xml");
                    conn.setRequestProperty("SOAPAction", SOAP_ACTION);

                    //push the request to the server address

                    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                    wr.write(body);
                    wr.flush();

                    //get the server response

                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder builder = new StringBuilder();
                    String line = null;

                    while ((line = reader.readLine()) != null) {


                        builder.append(line);
                        response = builder.toString();//this is the response, parse it in onPostExecute

                    }


                } catch (Exception e) {

                    e.printStackTrace();
                } finally {

                    try {

                        reader.close();
                    } catch (Exception e) {

                        e.printStackTrace();
                    }
                }


            } catch (Exception e) {

                e.printStackTrace();
            }

            return response;
        }

        /**
         * @see AsyncTask#onPostExecute(Object)
         */
        @Override
        protected void onPostExecute(String result) {



           try {

              Toast.makeText(this,"Response "+ result,Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

现在只需执行课程并观察神奇的事情:

runTask runner = new runTask();
runner.execute();

您可以使用DOM或SAX解析器解析响应以获取所需的值。 请随时要求进一步澄清。