Android使用kso​​ap2连接到webservice失败

时间:2017-03-14 06:10:05

标签: java android ksoap2

所以我有一个连接到w3schools webservice的问题。我正在尝试用android studio中的ksoap2库实现webservices.I已经硬编码一个值,一旦屏幕加载就返回一些东西但是我不认为我正在访问网络服务。请协助。

清单文件 >

  

的AndroidManifest.xml

        <?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="com.example.mjivan.webservicestut" >

            <application

                android:allowBackup="true"
                android:icon="@mipmap/ic_launcher"
                android:label="@string/app_name"

                android:supportsRtl="true"
                android:theme="@style/AppTheme" >
                <activity android:name=".MainActivity" >
                    <intent-filter>
                        <action android:name="android.intent.action.MAIN" />

                        <category android:name="android.intent.category.LAUNCHER" />
                    </intent-filter>
                </activity>
            </application>
            <uses-permission android:name="android.permission.INTERNET"></uses-permission>
        </manifest>
  

MainActivity.java

      package com.example.mjivan.webservicestut;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

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

public class MainActivity extends Activity {

    private TextView txt;
    private String celsius;
    private static final String SOAP_ACTION = "https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit";
    private static final String METHOD_NAME = "CelsiusToFahrenheit";
    private static final String NAMESPACE = "https://www.w3schools.com/";
    private static final String URL = "https://www.w3schools.com/xml/tempconvert.asmx";

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


        final EditText edt = (EditText) findViewById(R.id.value_to_convert);
        Button btn = (Button) findViewById(R.id.convert);
        txt = (TextView) findViewById(R.id.answer);
    }

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

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


                SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                soapEnvelope.dotNet = true;
                soapEnvelope.setOutputSoapObject(Request);

                HttpTransportSE aht = new HttpTransportSE(URL);
                try {
                    aht.call(SOAP_ACTION, soapEnvelope);
                    SoapPrimitive resultString = (SoapPrimitive) soapEnvelope.getResponse();
                    return "" + resultString;
                    //txt.setText("Status :" + resultString);
                } catch (Exception e) {

                    return null;
                }
            }
                @Override
                protected void onPostExecute (String result)
                {
                    TextView txt = (TextView) findViewById(R.id.answer);
                    txt.setText(result); // txt.setText(result);
                    // might want to change "executed" for the returned string passed
                    // into onPostExecute() but that is upto you
                }

                @Override
                protected void onPreExecute()
                {

                }


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

                }

        }



}
  
    

activity_main.xml中

  
  //layout file

 <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">


        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/value_to_convert" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Convert"
            android:id="@+id/convert"
            android:layout_gravity="center_horizontal" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/answer"
            android:textColor="@color/background_floating_material_dark" />
    </LinearLayout>
  

logcat的

      03-14 11:47:41.051 15992-15992/com.example.mjivan.webservicestut I/InjectionManager: Inside getClassLibPath caller 
03-14 11:47:41.051 15992-15992/com.example.mjivan.webservicestut W/System: ClassLoader referenced unknown path: /data/app/com.example.mjivan.webservicestut-1/lib/arm64
03-14 11:47:41.061 15992-15992/com.example.mjivan.webservicestut W/ResourcesManager: getTopLevelResources: /data/app/com.example.mjivan.webservicestut-1/base.apk / 1.0 running in com.example.mjivan.webservicestut rsrc of package com.example.mjivan.webservicestut
03-14 11:47:41.061 15992-15992/com.example.mjivan.webservicestut I/InjectionManager: Inside getClassLibPath + mLibMap{0=, 1=}
03-14 11:47:41.061 15992-15992/com.example.mjivan.webservicestut D/ResourcesManager: For user 0 new overlays fetched Null
03-14 11:47:43.191 15992-15992/com.example.mjivan.webservicestut W/System: ClassLoader referenced unknown path: /data/app/com.example.mjivan.webservicestut-1/lib/arm64
03-14 11:47:43.191 15992-15992/com.example.mjivan.webservicestut D/Minikin: FontFamily bestFont == NULL, so return vacant FakedFont
03-14 11:47:43.191 15992-15992/com.example.mjivan.webservicestut D/Minikin: FontFamily bestFont == NULL, so return vacant FakedFont
03-14 11:47:43.191 15992-15992/com.example.mjivan.webservicestut D/Minikin: FontFamily bestFont == NULL, so return vacant FakedFont
03-14 11:47:43.191 15992-15992/com.example.mjivan.webservicestut D/Minikin: FontFamily bestFont == NULL, so return vacant FakedFont
03-14 11:47:43.191 15992-15992/com.example.mjivan.webservicestut D/Minikin: FontFamily bestFont == NULL, so return vacant FakedFont
03-14 11:47:43.191 15992-15992/com.example.mjivan.webservicestut D/Minikin: FontFamily bestFont == NULL, so return vacant FakedFont
03-14 11:47:43.201 15992-15992/com.example.mjivan.webservicestut D/InjectionManager: InjectionManager
03-14 11:47:43.201 15992-15992/com.example.mjivan.webservicestut D/InjectionManager: fillFeatureStoreMap com.example.mjivan.webservicestut
03-14 11:47:43.201 15992-15992/com.example.mjivan.webservicestut I/InjectionManager: Constructor com.example.mjivan.webservicestut, Feature store :{}
03-14 11:47:43.201 15992-15992/com.example.mjivan.webservicestut I/InjectionManager: featureStore :{}
03-14 11:47:43.211 15992-15992/com.example.mjivan.webservicestut W/ResourcesManager: getTopLevelResources: /data/app/com.example.mjivan.webservicestut-1/base.apk / 1.0 running in com.example.mjivan.webservicestut rsrc of package com.example.mjivan.webservicestut
03-14 11:47:43.211 15992-15992/com.example.mjivan.webservicestut W/ResourcesManager: getTopLevelResources: /data/app/com.example.mjivan.webservicestut-1/base.apk / 1.0 running in com.example.mjivan.webservicestut rsrc of package com.example.mjivan.webservicestut
03-14 11:47:43.251 15992-15992/com.example.mjivan.webservicestut D/ClipboardExManager: no knox
03-14 11:47:43.261 15992-15992/com.example.mjivan.webservicestut D/Activity: performCreate Call Injection manager
03-14 11:47:43.261 15992-15992/com.example.mjivan.webservicestut I/InjectionManager: dispatchOnViewCreated > Target : com.example.mjivan.webservicestut.MainActivity isFragment :false
03-14 11:47:43.271 15992-15992/com.example.mjivan.webservicestut D/SecWifiDisplayUtil: Metadata value : SecSettings2
03-14 11:47:43.271 15992-15992/com.example.mjivan.webservicestut D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{b756f4e I.E...... R.....ID 0,0-0,0}
03-14 11:47:43.271 15992-16417/com.example.mjivan.webservicestut D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
03-14 11:47:43.351 15992-16417/com.example.mjivan.webservicestut D/libEGL: loaded /vendor/lib64/egl/libGLES_mali.so
03-14 11:47:43.361 15992-16417/com.example.mjivan.webservicestut D/libEGL: eglInitialize EGLDisplay = 0x7f990ff178
03-14 11:47:43.361 15992-16417/com.example.mjivan.webservicestut I/OpenGLRenderer: Initialized EGL, version 1.4

                                                                                   [ 03-14 11:47:43.371 15992:16417 D/         ]
                                                                                   ro.exynos.dss isEnabled: 0
03-14 11:47:43.371 15992-16417/com.example.mjivan.webservicestut D/mali_winsys: new_window_surface returns 0x3000,  [1440x2560]-format:1
03-14 11:47:43.391 15992-15992/com.example.mjivan.webservicestut W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
03-14 11:47:43.391 15992-15992/com.example.mjivan.webservicestut W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
03-14 11:47:43.391 15992-16417/com.example.mjivan.webservicestut D/libGLESv1: DTS_GLAPI : DTS is not allowed for Package : com.example.mjivan.webservicestut
03-14 11:47:43.481 15992-15992/com.example.mjivan.webservicestut D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
03-14 11:47:43.501 15992-15992/com.example.mjivan.webservicestut I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@a39acb5 time:30405778

1 个答案:

答案 0 :(得分:0)

在您的代码中,您没有使用任意线程或AsyncTask来执行网络操作。这就是你收到错误NetworkOnMainThreadException

的原因

将我的部分代码添加到AsyncTask

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

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


                SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                soapEnvelope.dotNet = true;
                soapEnvelope.setOutputSoapObject(Request);

                HttpTransportSE aht = new HttpTransportSE(URL);
                try {
                    aht.call(SOAP_ACTION, soapEnvelope);
                    SoapPrimitive resultString = (SoapPrimitive) soapEnvelope.getResponse();
            return ""+resultString;
                    txt.setText("Status :" + resultString);
                } catch (Excep

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed"); // txt.setText(result);
            // might want to change "executed" for the returned string passed
            // into onPostExecute() but that is upto you
        }

        @Override
        protected void onPreExecute() {}

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

要使用AsyncTask,您必须将其子类化。 AsyncTask使用泛型和变量。参数如下AsyncTask <TypeOfVarArgParams, ProgressValue, ResultValue>

AsyncTask通过execute()方法启动。此execute()方法调用doInBackground()onPostExecute()方法。

将TypeOfVarArgParams作为输入传递给doInBackground()方法。 ProgressValue用于获取进度信息,ResultValue必须从doInBackground()方法返回。此参数作为参数传递给onPostExecute()

doInBackground()方法包含应在后台线程中执行的编码指令。此方法在单独的线程中自动运行。

onPostExecute()方法再次与用户界面线程同步,并允许更新。一旦doInBackground()方法完成,框架就会调用此方法。