使用Android连接.net Webservice

时间:2016-09-01 05:24:15

标签: android android-ksoap2 networkonmainthread

Webservice类代码

public class WebService {

    String namespace = "http://www.webserviceX.NET/";
    private String url = "http://www.webservicex.net/ConvertWeight.asmx";

    String SOAP_ACTION;
    SoapObject request = null, objMessages = null;
    SoapSerializationEnvelope envelope;
    AndroidHttpTransport androidHttpTransport;

    WebService() {
    }
    protected void SetEnvelope() {

        try {

            // Creating SOAP envelope
            envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            //You can comment that line if your web service is not .NET one.
            envelope.dotNet = true;

            envelope.setOutputSoapObject(request);
            androidHttpTransport = new AndroidHttpTransport(url);
            androidHttpTransport.debug = true;

        } catch (Exception e) {
            System.out.println("Soap Exception---->>>" + e.toString());
        }
    }

    // MethodName variable is define for which webservice function  will call
    public String getConvertedWeight(String MethodName, String weight,
                                     String fromUnit, String toUnit)
    {

        try {
            SOAP_ACTION = namespace + MethodName;

            //Adding values to request object
            request = new SoapObject(namespace, MethodName);

            //Adding Double value to request object
            PropertyInfo weightProp =new PropertyInfo();
            weightProp.setName("Weight");
            weightProp.setValue(weight);
            weightProp.setType(double.class);
            request.addProperty(weightProp);

            //Adding String value to request object
            request.addProperty("FromUnit", "" + fromUnit);
            request.addProperty("ToUnit", "" + toUnit);

            SetEnvelope();

            try {

                //SOAP calling webservice
                androidHttpTransport.call(SOAP_ACTION, envelope);

                //Got Webservice response
                String result = envelope.getResponse().toString();

                return result;

            } catch (Exception e) {
                // TODO: handle exception
                return e.toString();
            }
        } catch (Exception e) {
            // TODO: handle exception
            return e.toString();
        }
    }
} 

我更新的活动代码:

public class CheckDNLoginActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final Button webserviceCallButton = (Button) findViewById(R.id.webservice);
        final TextView webserviceResponse = (TextView) findViewById(R.id.webserviceResponse);

        webserviceCallButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                webserviceResponse.setText("Requesting to server .....");

                new ExecuteService().execute();

             }
         });
     }


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

            @Override
            protected String doInBackground(String... params) {
                //Create Webservice class object
                WebService com = new WebService();

                // Initialize variables
                String weight   = "18000";
                String fromUnit = "Grams";
                String toUnit   = "Kilograms";

                //Call Webservice class method and pass values and get response
                String aResponse = com.getConvertedWeight("ConvertWeight", weight, fromUnit, toUnit);

                //Alert message to show webservice response
                Toast.makeText(getApplicationContext(), weight+" Gram= "+aResponse+" Kilograms",
                        Toast.LENGTH_LONG).show();

                Log.i("AndroidExampleOutput", "----"+aResponse);
                return aResponse;
            }

            @Override
            protected void onPostExecute(String result) {
                webserviceResponse.setText("Response : "+ result);

            }

            @Override
            protected void onPreExecute() {}
        }
}

这是我更新的logcat。当我运行我的应用程序时,我得到错误:

FATAL EXCEPTION: main
      Process: com.example.dell.piechart2, PID: 2762
      java.lang.NullPointerException
          at com.example.dell.piechart2.CheckDNLoginActivity$ExecuteService.onPostExecute(CheckDNLoginActivity.java:63)
          at com.example.dell.piechart2.CheckDNLoginActivity$ExecuteService.onPostExecute(CheckDNLoginActivity.java:38)
          at android.os.AsyncTask.finish(AsyncTask.java:632)
          at android.os.AsyncTask.access$600(AsyncTask.java:177)
          at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
          at android.os.Handler.dispatchMessage(Handler.java:102)
          at android.os.Looper.loop(Looper.java:136)
          at android.app.ActivityThread.main(ActivityThread.java:5017)
          at java.lang.reflect.Method.invokeNative(Native Method)
          at java.lang.reflect.Method.invoke(Method.java:515)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
          at dalvik.system.NativeStart.main(Native Method)

有什么问题?请帮我。我在这里发布我的完整logcat。你也可以检查一下。 提前谢谢。

3 个答案:

答案 0 :(得分:0)

您需要使用Async Task类,如下所示

首先按以下方式更改按钮点击事件

  webserviceCallButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            webserviceResponse.setText("Requesting to server .....");

            new ExecuteService().execute();

        }
    });

现在,请检查整个活动代码

    public class CheckDNLoginActivity extends Activity {

        Button webserviceCallButton;
        TextView webserviceResponse;

        @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            webserviceCallButton = (Button) findViewById(R.id.webservice);
            webserviceResponse = (TextView) findViewById(R.id.webserviceResponse);

            webserviceCallButton.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {

                    webserviceResponse.setText("Requesting to server .....");

                    new ExecuteService().execute();

                 }
             });
         }


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

            @Override
            protected String doInBackground(String... params) {
                //Create Webservice class object
                WebService com = new WebService();

                // Initialize variables
                String weight   = "18000";
                String fromUnit = "Grams";
                String toUnit   = "Kilograms";

                //Call Webservice class method and pass values and get response
                String aResponse = com.getConvertedWeight("ConvertWeight", weight, fromUnit, toUnit);

                //Alert message to show webservice response
                Toast.makeText(getApplicationContext(), weight+" Gram= "+aResponse+" Kilograms",
                    Toast.LENGTH_LONG).show();

                Log.i("AndroidExampleOutput", "----"+aResponse);
                return aResponse;
            }

            @Override
            protected void onPostExecute(String result) {
                webserviceResponse.setText("Response : "+ result);

            }

            @Override
            protected void onPreExecute() {}
        }
}

答案 1 :(得分:0)

当应用程序尝试在其主线程上执行网络操作时,抛出

NetworkOnMainThreadException

您可以使用AsyncTask进行网络操作。

这是AsyncTask代码,

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

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        webserviceResponse.setText("Requesting to server .....");
    }

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

        //Create Webservice class object
        WebService com = new WebService();

        // Initialize variables
        String weight   = params[1];
        String fromUnit = params[2];
        String toUnit   = params[3];

        //Call Webservice class method and pass values and get response
        return com.getConvertedWeight(params[0], weight, fromUnit, toUnit);
    }

    @Override
    protected void onPostExecute(String aResponse) {
        webserviceResponse.setText("Response : "+aResponse);
    }
}

这就是您致电AyncTask

的方式
webserviceCallButton.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        new MyNetworkTask().execute("ConvertWeight", "18000", "Grams", "Kilograms");

    }

});

有关详细信息,请参阅this SO主题。

答案 2 :(得分:0)

试试这个

 public class request extends AppCompatActivity {
 TextView webserviceResponse;

String aResponse="nul";

String f_name="";

WebserviceCall com = new WebserviceCall();

Button webserviceCallButton;

@Override

  protected void onCreate(Bundle savedInstanceState) {

     super.onCreate(savedInstanceState);

    setContentView(R.layout.request);

     webserviceCallButton = (Button) findViewById(R.id.button);
     webserviceResponse = (TextView) findViewById(R.id.textView);

    webserviceCallButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            f_name   = "1";

            new LongOperation().execute("");


        }
    });

}
private class LongOperation extends AsyncTask<String, Void, String> {

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


        //Create Webservice class object

        // Initialize variables

        //Call Webservice class method and pass values and get response
        aResponse = com.getchange_liveserver("wb", f_name);

        //Alert message to show webservice response

        Log.i("AndroidExampleOutput", "----"+aResponse);

      //  webserviceResponse.setText("Executed"); // txt.setText(result);
        // might want to change "executed" for the returned string passed

        // into onPostExecute() but that is upto you
        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {


        webserviceResponse.setText("Response : "+aResponse);


    }









 @Override
    protected void onPreExecute() {               
  webserviceResponse.setText("Requesting to server .....");
    }

    @Override
    protected void onProgressUpdate(Void... values) {}
}

}