3

嗨,我尝试使用 Android 从 Web 服务读取任何数据,但每次尝试都遇到问题

今天我尝试从 3schools 网站阅读 Web 服务

使用本准则

package com.example.lo2i03;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
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.HttpTransportSE;

public class MainActivity extends Activity {

    private static String SOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";
    private static String NAMESPACE = "http://tempuri.org/";
    private static String METHOD_NAME = "CelsiusToFahrenheit";
    private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         tv = (TextView)findViewById(R.id.txt);
         SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);             
         request.addProperty("Celsius","32"); 
         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
         envelope.setOutputSoapObject(request);
         envelope.dotNet = true;
         try
         {
               HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);          
               androidHttpTransport.call(SOAP_ACTION, envelope);             
               SoapObject result = (SoapObject)envelope.getResponse();
               tv.setText(result.getProperty(0).toString());
         }
         catch (Exception e) 
         {
              tv.setText("Error");
         }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

知道我添加了清单访问 Internet 的权限

它直接进入一个捕获块......

清单文件

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.lo2i03.MainActivity"
            android:label="@string/app_name" >
            <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>

安卓版本:4.2 - 4.2


LogCat 错误看起来像

11-24 01:28:29.065: E/Trace(13408): error opening trace file: No such file or directory (2)
11-24 01:28:29.195: D/AndroidRuntime(13408): Shutting down VM
11-24 01:28:29.195: W/dalvikvm(13408): threadid=1: thread exiting with uncaught exception (group=0x412862a0)
11-24 01:28:29.195: E/AndroidRuntime(13408): FATAL EXCEPTION: main
11-24 01:28:29.195: E/AndroidRuntime(13408): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lo2i03/com.example.lo2i03.MainActivity}: android.os.NetworkOnMainThreadException
11-24 01:28:29.195: E/AndroidRuntime(13408):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at android.os.Looper.loop(Looper.java:137)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at android.app.ActivityThread.main(ActivityThread.java:4898)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at java.lang.reflect.Method.invokeNative(Native Method)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at java.lang.reflect.Method.invoke(Method.java:511)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at dalvik.system.NativeStart.main(Native Method)
11-24 01:28:29.195: E/AndroidRuntime(13408): Caused by: android.os.NetworkOnMainThreadException
11-24 01:28:29.195: E/AndroidRuntime(13408):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at org.ksoap2.transport.ServiceConnectionSE.connect(ServiceConnectionSE.java:76)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:146)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:95)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at com.example.lo2i03.MainActivity.onCreate(MainActivity.java:35)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at android.app.Activity.performCreate(Activity.java:5191)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
11-24 01:28:29.195: E/AndroidRuntime(13408):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
11-24 01:28:29.195: E/AndroidRuntime(13408):    ... 11 more

新的 LOGCAT (1.0)

11-24 16:28:28.850: E/Trace(25195): error opening trace file: No such file or directory (2)
11-24 16:28:28.995: D/libEGL(25195): loaded /system/lib/egl/libEGL_mali.so
11-24 16:28:28.995: D/libEGL(25195): loaded /system/lib/egl/libGLESv1_CM_mali.so
11-24 16:28:29.000: D/libEGL(25195): loaded /system/lib/egl/libGLESv2_mali.so
11-24 16:28:29.000: D/(25195): Device driver API match
11-24 16:28:29.000: D/(25195): Device driver API version: 10
11-24 16:28:29.000: D/(25195): User space API version: 10 
11-24 16:28:29.000: D/(25195): mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Wed Sep 12 17:53:53 KST 2012 
11-24 16:28:29.030: D/OpenGLRenderer(25195): Enabling debug mode 0
11-24 16:28:31.215: D/dalvikvm(25195): GC_CONCURRENT freed 214K, 10% free 12330K/13575K, paused 13ms+13ms, total 40ms
11-24 16:28:39.615: W/IInputConnectionWrapper(25195): getSelectedText on inactive InputConnection
11-24 16:28:39.615: W/IInputConnectionWrapper(25195): setComposingText on inactive InputConnection
11-24 16:28:39.615: W/IInputConnectionWrapper(25195): getExtractedText on inactive InputConnection

了解我使用 (WiFi) 访问互联网的知识。

有什么建议吗?

4

4 回答 4

2

NetworkOnMainThreadException 意味着您正在 UI 线程中运行 http 请求代码。

尝试这样的事情:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         tv = (TextView)findViewById(R.id.txt);
         final SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);             
         request.addProperty("Celsius","32"); 
         final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
         envelope.setOutputSoapObject(request);
         envelope.dotNet = true;
         new AsyncTask<Void, Void, Boolean>() {
            SoapObject obj;

            @Override
            protected Boolean doInBackground(Void... params) {
                   //here you can do your background network job
                try
                 {
                       HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);          
                       androidHttpTransport.call(SOAP_ACTION, envelope);             
                       obj = (SoapObject)envelope.getResponse();

                       return true;
                 }
                 catch (Exception e) 
                 {
                     e.printStackTrace();   
                         return false;                    
                 }
            }
            @Override
            protected void onPostExecute(Boolean result) {
             //here you can do your UI job
                if (!result) 
                    tv.setText("Error");
                else 
                    tv.setText(obj.getProperty(0).toString());
                super.onPostExecute(result);
            }
        }.execute();

    } 
于 2012-11-23T23:21:25.560 回答
1

尝试:

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope. dotNet= true;
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
    try {
        androidHttpTransport.call(SOAP_ACTION, envelope);                    
        SoapPrimitive result = (SoapPrimitive) envelope.getResponse();          
        String r = result.toString();
        return r;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   

如果您需要返回对象或数组列表,我可以发布解决方案...

于 2012-11-23T18:57:46.630 回答
1

从肥皂网络服务获取对象:

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope. dotNet= true;
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
    try {
        androidHttpTransport.call(SOAP_VERATENDIMENTO, envelope);                    
        SoapObject result = (SoapObject) envelope.getResponse();            
        YourClass yourClass = new YourClass();
        if (result == null){
            return null;
        } else {
            yourClass.setName(result.getProperty("name").toString());
            yourClass.setEmail(result.getProperty("email").toString());
            return yourClass;               
        }                       
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }               
    return null;

返回 arraylist 做:

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope. dotNet= true;
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
    try {
        androidHttpTransport.call(SOAP_VERMENSAGENS, envelope);                    
        SoapObject result = (SoapObject) envelope.getResponse();            

        List<YourClassObject> yourList = new ArrayList<YourClassObject>();
        if (result == null){
            return null;
        } else {
            for(int i =0; i < result.getPropertyCount(); i++){
                SoapObject soap = (SoapObject) result.getProperty(i);
                YourClassObject yourClass = new YourClassObject();
                yourClass.setName(soap.getProperty("name").toString()));
                yourClass.setEmail(soap.getProperty("email").toString()));
                yourList.add(yourClass);
            }
            return yourList;
        }                       
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }               
    return null;
于 2012-11-26T10:28:54.790 回答
1

在清单文件中添加对 Internet 的权限

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

然后在您的活动中,您在哪里运行您的 http 请求,在 setContentView 之前添加此行,如下所示

 setContentView(R.layout.activity_profile);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
于 2015-05-14T07:51:59.650 回答