首页 > 解决方案 > 使用 OKHttp 发出 GET 请求时出现“无法执行 android:onClick 的方法”异常

问题描述

我正在尝试在单击按钮时使用 OKHttp 创建 GET 请求。单击按钮时,会向特定 url 发出一个请求,该 url 会获取一些 JSON 数据。以下是代码片段:

public static String sendGet(final String url, final String token) throws IOException, JSONException {
            Request request = new Request.Builder()
                    .url(url)
                    //This adds the token to the header.
                    .addHeader("Authorization", "Bearer " + token)
                    .addHeader("Content-Type","application/json")
                    .build();

            try{
                Response response = client.newCall(request).execute();
                System.out.println(response);
                if (!response.isSuccessful()){
                    throw new IOException("Unexpected Code " + response);
                }
                System.out.println(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
}

以下是例外情况:

FATAL EXCEPTION: main
    Process: com.collins.ped.bw, PID: 15532
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
        at android.view.View.performClick(View.java:6308)
        at android.widget.TextView.performClick(TextView.java:11202)
        at android.view.View$PerformClick.run(View.java:23969)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6823)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)

标签: javaandroidokhttp

解决方案


推荐阅读