簡體   English   中英

Android使用kso​​ap2連接到Web服務失敗

[英]Android using ksoap2 to connect to webservice failing

所以我在連接到w3schools網絡服務時遇到了一些問題。我正在嘗試使用android studio中的ksoap2庫來實現網絡服務。我已經硬編碼了一個值,以便在屏幕加載后立即返回一些東西,但我不認為我正在使用網絡服務。請協助。

清單文件>

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

在您的代碼中,您沒有使用任何線程或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使用泛型和varargs。 這些參數是以下AsyncTask <TypeOfVarArgParams, ProgressValue, ResultValue>

AsyncTask通過execute()方法啟動。 此execute()方法調用doInBackground()onPostExecute()方法。

TypeOfVarArgParams作為輸入傳遞到doInBackground()方法中。 ProgressValue用於進度信息, ResultValue必須從doInBackground()方法返回doInBackground() 該參數作為參數傳遞給onPostExecute()

doInBackground()方法包含應在后台線程中執行的編碼指令。 此方法在單獨的線程中自動運行。

onPostExecute()方法再次使其自身與用戶界面線程同步,並允許對其進行更新。 doInBackground()方法完成后,框架將調用此方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM