繁体   English   中英

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

[英]Trying to access webmethod from android app using OkHttp3

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

托管在http:// someaddress .com / HelloWorld的Web服务

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应用程序来访问网络服务HelloWorld和onResponse,祝酒“成功”。 我的目标是在以后的迭代中以此为基础并利用更多的Web服务。 但是,以下内容不断返回各种错误,这些错误在搜索时不会返回与我的问题相关的解决方案。 目前,我能提出的最好的建议可能是活动问题。 破坏代码并遵循堆栈跟踪也不会返回任何对我而言突出的内容。 任何帮助将不胜感激。 提前致谢。

更新

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

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$2.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()会引发我所看到的特定错误。 我认为这与Android使用的Views有关。 只需删除此代码,然后将其替换为可以在onResponse方法之外引用的变量即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM