关于执行soap请求的NetworkOnMainThreadException

时间:2014-04-23 09:11:38

标签: android soap android-ksoap2

我正在尝试根据此WSDL方案执行soap请求:

http://pastebin.com/UT3t5XdQ

这是我的应用代码:

private final String SOAP_ACTION = "https://t4t.services.telenet.be/TelemeterService";
    private final String NAMESPACE = "http://www.telenet.be/TelemeterService/";
    private final String METHOD_NAME = "RetrieveUsageRequestType";
    private final String URL = "https://t4t.services.telenet.be/TelemeterService.wsdl";

    private Button sendButton;
    private TextView responseView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendButton = (Button) findViewById(R.id.send);
        responseView = (TextView) findViewById(R.id.response);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

                //Parameters
                request.addProperty("UserId","test@telenet.be");
                request.addProperty("Password","test");

                //Version Soap
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

                envelope.setOutputSoapObject(request);
                envelope.dotNet = true;

                try {
                    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                    //Call the webservice
                    androidHttpTransport.call(SOAP_ACTION, envelope);

                    // Get the result
                    SoapObject result = (SoapObject)envelope.bodyIn;

                    if(result != null)
                    {
                        Log.d("Debug","Result");
                        responseView.setText(result.getProperty(0).toString());
                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(), "No Response", Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

在我的清单中,我添加了互联网许可。

我遇到了这个例外:

04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ android.os.NetworkOnMainThreadException
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at java.net.InetAddress.getAllByName(InetAddress.java:214)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:254)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at org.ksoap2.transport.ServiceConnectionSE.openOutputStream(ServiceConnectionSE.java:126)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:185)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:118)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:113)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at test.example.com.MainActivity$1.onClick(MainActivity.java:54)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at android.view.View.performClick(View.java:4438)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at android.view.View$PerformClick.run(View.java:18422)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at android.os.Looper.loop(Looper.java:136)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5017)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-23 09:05:57.933    1454-1454/test.example.com W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)

6 个答案:

答案 0 :(得分:1)

当应用程序尝试在其主线程上执行网络操作时,抛出此异常。在AsyncTask中运行您的代码:

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

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                }
                @Override
                protected String doInBackground(String... params) {

                     SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

                    //Parameters
                    request.addProperty("UserId","test@telenet.be");
                    request.addProperty("Password","test");

                    //Version Soap
                    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

                    envelope.setOutputSoapObject(request);
                    envelope.dotNet = true;

                    try {
                        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                        //Call the webservice
                        androidHttpTransport.call(SOAP_ACTION, envelope);

                        // Get the result
                        SoapObject result = (SoapObject)envelope.bodyIn;


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

                    return result.toString() ;
                }

                @Override
                protected void onPostExecute(String result) {
                    super.onPostExecute(result);                
                     if(result != null)
                    {
                        Log.d("Debug","Result");
                        responseView.setText(result.getProperty(0).toString());
                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(), "No Response", Toast.LENGTH_LONG).show();
                    }
                }

            }

执行按钮点击中的AsyncTask,如下所示,

sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
  new SetTreasureBoxAsyncTask().execute(); 
});

答案 1 :(得分:0)

创建Async类并在doinbackground()方法中添加soap请求代码。 并在按钮单击事件上执行异步类。

答案 2 :(得分:0)

您可以从主线程访问网络功能。你需要开始一个外国线程。

sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        new Thread(){

            @Override
                public void run() {

            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

            //Parameters
            request.addProperty("UserId","test@telenet.be");
            request.addProperty("Password","test");

            //Version Soap
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;

            try {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                //Call the webservice
                androidHttpTransport.call(SOAP_ACTION, envelope);

                // Get the result
                SoapObject result = (SoapObject)envelope.bodyIn;

                if(result != null)
                {
                    Log.d("Debug","Result");
                    responseView.setText(result.getProperty(0).toString());
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "No Response", Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        }}.start();
    });

您也可以使用AsyncTask。

答案 3 :(得分:0)

您不允许在主线程上执行(可能)长时间运行的进程。所有网络操作在单独的后台线程中运行,因为它们会冻结UI。这通常会导致您的应用崩溃,因为它的用户界面被冻结时无响应。

结帐Processes and Threads。您会发现AsyncTask在各种场合都非常容易使用。

答案 4 :(得分:0)

试试这个..

class SoapConnection extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... urls) {
        String values = "";
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

            //Parameters
            request.addProperty("UserId","test@telenet.be");
            request.addProperty("Password","test");

            //Version Soap
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;

            try {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                //Call the webservice
                androidHttpTransport.call(SOAP_ACTION, envelope);

                // Get the result
                SoapObject result = (SoapObject)envelope.bodyIn;

                if(result != null)
                {
                    values = result.getProperty(0).toString();
                }
                else
                {
                    values = "No Response";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    }

    protected void onPostExecute(String result) {
            if(result.equlas("No Response"))
                  Toast.makeText(getApplicationContext(), "No Response", Toast.LENGTH_LONG).show();
            else
                  responseView.setText(result);
    }
}

称之为

sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                       new SoapConnection().execute();
            }
});

答案 5 :(得分:0)

我解决了Spring break建议的问题。

private Button sendButton;
private TextView responseView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sendButton = (Button) findViewById(R.id.send);
    responseView = (TextView) findViewById(R.id.response);

    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new SetTreasureBoxAsyncTask().execute();
        }

    });
}
private class SetTreasureBoxAsyncTask extends AsyncTask<String, String, String>
{
    SoapObject result = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected String doInBackground(String... params) {



        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        //Parameters
        request.addProperty("UserId","test@telenet.be");
        request.addProperty("Password","test");

        //Version Soap
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

        envelope.setOutputSoapObject(request);
        envelope.dotNet = true;

        try {
            HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

            //Call the webservice
            androidHttpTransport.call(SOAP_ACTION, envelope);

            // Get the result
            result = (SoapObject)envelope.bodyIn;


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

        if(result != null)
            return result.toString();
        else
            return null;
    }

    @Override
    protected void onPostExecute(String res) {
        super.onPostExecute(res);
        if(result != null)
        {
            Log.d("Debug", "Result");
            responseView.setText(result.getProperty(0).toString());
        }
        else
        {
            Toast.makeText(getApplicationContext(), "No Response", Toast.LENGTH_LONG).show();
        }
    }

}

问题是任务花了很长时间。