2

我有一个代码,它调用 www,tempuri.org 提供的网络服务。当我尝试运行应用程序时,应用程序意外停止并显示消息 - “不幸的是,MyTest 已停止”.. 这是我的 java 文件 -

MainActivity.java :-

package com.example.mytest;


import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;

import org.ksoap2.transport.HttpTransportSE;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
    public static final String SOAP_ACTION = "http://tempuri.org/CelciusToFarenheit";
    public static final String METHOD_NAME = "CelciusToFarenheit";
    public static final String NAMESPACE= "http://tempuri.org/";
    public static final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
    TextView tv;
    SoapEnvelope se;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv= (TextView) findViewById(R.id.TextView01);

        SoapObject Request=new SoapObject(NAMESPACE,METHOD_NAME);
        Request.addProperty("Celcius","32");
        SoapSerializationEnvelope sse = new SoapSerializationEnvelope (se.VER11);
        sse.dotNet=true;
        sse.setOutputSoapObject(Request);
        HttpTransportSE abt = new HttpTransportSE(URL);
        try
        {
            abt.call(SOAP_ACTION,se);
              SoapObject resultString=(SoapObject)sse.getResponse();   
              String resultData=resultString.getProperty(0).toString();

            tv.setText("Status :"+resultString);
        }
        catch(Exception 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.main, menu);
        return true;
    }

}

activity_main.xml :-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

logcat如下 -

08-10 01:35:10.421: E/AndroidRuntime(1077): FATAL EXCEPTION: main
08-10 01:35:10.421: E/AndroidRuntime(1077): java.lang.NoClassDefFoundError: org.ksoap2.serialization.SoapObject
08-10 01:35:10.421: E/AndroidRuntime(1077):     at com.example.mytest.MainActivity.onCreate(MainActivity.java:30)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at android.app.Activity.performCreate(Activity.java:5133)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at android.os.Looper.loop(Looper.java:137)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at android.app.ActivityThread.main(ActivityThread.java:5103)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at java.lang.reflect.Method.invokeNative(Native Method)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at java.lang.reflect.Method.invoke(Method.java:525)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-10 01:35:10.421: E/AndroidRuntime(1077):     at dalvik.system.NativeStart.main(Native Method)

我是使用 android 开发 Web 服务的新手。你能建议我吗,该怎么办?

4

4 回答 4

1

您不能在主 ui 线程上进行网络相关操作。您应该使用ThreadAsyncTask

您正在 ui 线程上执行网络相关操作。您将获得NetworkOnMainThredExceptionapi 级别 11 及以上。

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

AsyncTask 文档:

http://developer.android.com/reference/android/os/AsyncTask.html

我怀疑您在 libs 文件夹下没有 jar 文件 确保您已将 ksoap jar 文件添加到您的 libs 文件夹中。

http://code.google.com/p/ksoap2-android/downloads/detail?name=ksoap2-android-assembly-2.4-jar-with-dependencies.jar&下载

您也可以使用线程,但不能从后台线程更新 ui。您应该在 ui 线程上更新 ui。所以 asynctask 让它变得更容易。

示例:华氏度到摄氏度。同样,您可以为 CelciusToFarenheit 调用适当的 soap 方法。要遵循的相同步骤

 public class FirstScreen extends Activity
 {
 private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
 private static String NAMESPACE = "http://tempuri.org/";
 private static String METHOD_NAME1 = "FahrenheitToCelsius";
 private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
SoapObject result;
 Button b;
 EditText et;
 int value;
 TextView tv;
 ProgressDialog pd;

 @Override
  public void onCreate(Bundle savedInstanceState)
  {

    super.onCreate(savedInstanceState);
    pd= new ProgressDialog(this);
    pd.setTitle("Making Soap Request");
    setContentView(R.layout.activity_main); 
    b= (Button) findViewById(R.id.button1);
    tv= (TextView) findViewById(R.id.textView2);
    et= (EditText) findViewById(R.id.ed);
    b.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            value=Integer.parseInt(et.getText().toString());
            new one1().execute();
        }

    });


}

 private class one1 extends AsyncTask<String, Integer, SoapObject> {

  protected void onPreExecute()
  {
      pd.show();
  }
protected SoapObject doInBackground(String... arg0) {
    // TODO Auto-generated method stub
       //Initialize soap request + add parameters
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);    

    //Use this to add parameters
    request.addProperty("Fahrenheit",value);         

    //Declare the version of the SOAP request
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);          

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

    try {
          HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);                
          androidHttpTransport.call(SOAP_ACTION1, envelope);
          result = (SoapObject)envelope.bodyIn;

    } catch (Exception e) {

          e.printStackTrace();

    }           
    return result;
}

 protected void onPostExecute(SoapObject result)
 {
  pd.dismiss();
if(result != null)
{
      tv.setText("Result = "+result.getProperty(0).toString());
}
else
{
      Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
}

}

我的activity_main.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="FahrenheitToCelsius" />

<EditText
    android:id="@+id/ed"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="43dp" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="37dp"
    android:text="MakeRequest" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="20dp"
    android:text="Result" />

 </LinearLayout>

最后确保您在清单文件中具有 Internet 权限

      <uses-permission android:name="android.permission.INTERNET"/>

快照。

在此处输入图像描述

于 2013-08-10T05:51:31.673 回答
1

Nirmal 上面的回答对我有用。但是,我必须按如下方式更新操作和命名空间:

private static final String SOAP_ACTION = "http://www.w3schools.com/webservices/CelsiusToFahrenheit";
private static final String NAMESPACE = "http://www.w3schools.com/webservices/";

我通过以下方式弄清楚了正确的值应该是什么:

  1. 进入网络服务页面:http ://www.w3schools.com/webservices/tempconvert.asmx

  2. 单击服务描述链接:http ://www.w3schools.com/webservices/tempconvert.asmx?WSDL

  3. 在该 xml 中搜索字符串(不区分大小写)“action”和“namespace”,然后使用它们具有的值

于 2014-04-10T19:21:19.817 回答
1

像这样使用:

XML:

      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
       android:layout_height="match_parent" >

<Button
    android:id="@+id/web_service"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="112dp"
    android:layout_marginTop="146dp"
    android:text="Web Service" />

<TextView
    android:id="@+id/fetch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="TextView" />

  </RelativeLayout>

活动:

  public class MainActivity extends Activity {

Button web_service;
TextView fetch_service;

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

    fetch_service = (TextView) findViewById(R.id.fetch);
    web_service = (Button) findViewById(R.id.web_service);
    web_service.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            myasynctask MAT = new myasynctask();
            MAT.execute();
        }
    });
}

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

    String str;
    private static final String SOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";
    private static final String METHOD_NAME = "CelsiusToFahrenheit";
    private static final String NAMESPACE = "http://tempuri.org/";
    private static final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";

    @Override
    protected String doInBackground(String... params) {
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        request.addProperty("Celsius", "32");

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);

        HttpTransportSE ht = new HttpTransportSE(URL);

        try {
            ht.call(SOAP_ACTION, envelope);
            final SoapPrimitive response = (SoapPrimitive) envelope
                    .getResponse();
            str = response.toString();

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

        }
        Log.d("WebRespone", str);
        return str;
    }

    @Override
    public void onPostExecute(String result) {
        // TODO Auto-generated method stub
        Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
        fetch_service.setText(result);
        super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }

}
    }

清单: 在清单中添加以下内容

 <uses-permission android:name="android.permission.INTERNET"/>

输出: 在此处输入图像描述

希望这会帮助你。

于 2013-08-10T05:45:58.600 回答
0

我收到了同样的例外:

 java.lang.NoClassDefFoundError: org.ksoap2.serialization.SoapObject at    
 com.example.soap_ksoap2_lino.MainActivity.onCreate(MainActivity.java:29)

我认为来自 code.google.com/p/ksoap2-android 的 .jar 文件仅用于编译。它没有课程。所有其他 .jars 也不起作用。我已经放弃了 KSOAP2 API 策略,现在尝试使用 .jar 已经存在于 Eclipse ADT 中的 HttpPost。

这是我的代码:从 Android 发送 SOAP 请求。服务器响应:“服务器无法处理请求。”

我收到来自 w3schools 服务器的响应,但是服务器响应:“服务器无法处理请求”。

于 2013-08-14T11:20:05.407 回答