尝试使用 OkHttp3 从 android 应用程序访问 webmethod

Trying to access webmethod from android app using OkHttp3

我正在尝试使用以下代码创建网络方法,然后使用 OkHttp 从 android 应用程序中使用它:

webservice 托管于 http://someaddress.com/HelloWorld

using GLS.GLIS.Core;
using System.IO;
using GLS.GLIS.ApplicationServices.Settings;

namespace GLS.GLIS.Web.Ax
{

  [WebService(Namespace = "http://tempuri.org/")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  [System.ComponentModel.ToolboxItem(false)]
  // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
  [System.Web.Script.Services.ScriptService]
  public class Wireless : System.Web.Services.WebService
  {

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
}

以上作品,生产代码

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.whirlpool.ad.na.gruves1.glisweb">

  <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    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 android:name="android.permission.ACCESS_NETWORK_STATE"/>

</manifest>

MainActivity.java

package com.whirlpool.ad.na.gruves1.glisweb;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity {



  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    Button HelloWorldbtn = (Button) findViewById(R.id.btn1);

    HelloWorldbtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            onHelloWorld(v);
        }
    });
  }



  public void onHelloWorld (View v) {
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url("http://<someaddress>.com/HelloWorld")
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Toast toast = Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT);
            toast.show();
        }
    });
  }
}

目标是使用 android 应用程序访问 Web 服务 HelloWorld 和 onResponse,toast "Success"。我的目标是在未来的迭代中以此为基础并利用更多的网络服务。但是,以下内容保留 returning 各种错误,在搜索时,不会 return 与我的问题相关的解决方案。目前我能想到的最好的办法就是它可能是一个 activity 问题。破坏代码并跟踪堆栈跟踪也不会 return 任何对我来说突出的东西。任何帮助将不胜感激。提前致谢。

更新

以下是我在模拟器中 运行 时得到的错误:

E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
  Process: glisweb, PID: 2749
  java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
  at android.os.Handler.<init>(Handler.java:200)
  at android.os.Handler.<init>(Handler.java:114)
  at android.widget.Toast$TN.<init>(Toast.java:345)
  at android.widget.Toast.<init>(Toast.java:101)
  at android.widget.Toast.makeText(Toast.java:259)
  at glisweb.MainActivity.onResponse(MainActivity.java:54)
  at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135)
  at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
  at java.lang.Thread.run(Thread.java:818)

这让我进行了大量的实验和探索,但我终于找到了解决这个错误的方法。此解决方案的要点是,您应该小心在 newCall 函数中的 onFailure 和 onResponse 方法中放置的代码。例如:

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Toast toast = Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT);
        toast.show();
    }

在 onResponse 中,使用函数 toast.show() 会抛出我看到的特定错误。我相信这与 Views Android 的使用有关。只需删除此代码并将其替换为可以在 onResponse 方法之外引用的变量。