【问题标题】:random com.android.volley.NoConnection error, java.io.InterruptedIOException, statuscode=0随机 com.android.volley.NoConnection 错误,java.io.InterruptedIOException,statuscode=0
【发布时间】:2015-07-01 10:32:07
【问题描述】:

我有一个使用 volley 框架从 PHP 服务器端脚本获取数据的原生 android 应用。

它在大多数时候运行良好,但我有 20% 的失败率。

错误提示:

com.android.volley.NoConnection, java.io.InterruptedIOException。

我调试发现statuscode = 0,显然是错的。

我不知道可能是什么原因?由于它大部分时间都在工作,所以应该没有明显的错误代码。

仅供参考,服务器端的那些 PHP 脚本非常适合我的 IOS 应用程序。

请允许我在这里发布我的代码:

retryConnBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            txtOut.append("\n");
            txtOut.append("Button with Retry Click");
            Log.d("Click", "Button Click");
            final String url = "https://www.myserver.com/api/getBalanceInfoTest?token=7ff3317a4f3dc07d0c297a7d16d2049c&t=" + System.currentTimeMillis();
            //final String url = "http://192.168.1.23/base/test/";
            JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            txtOut.append("\n");
                            txtOut.append("Result with Retry:");
                            txtOut.append(response.toString());
                            Log.d("Response", response.toString());
                            VolleyLog.e("Response:", response.toString());
                        }
                    },
                    new Response.ErrorListener(){
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            txtOut.append("\n");
                            txtOut.append("Error with Retry:");
                            txtOut.append(error.toString());
                            Log.d("Error.Response", error.toString());
                            VolleyLog.e("Error:", error.getMessage());
                        }
                    });

            getRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(getRequest);
            queue.start();
        }
    });


}

更多信息,我的PHP 脚本的输出是: {"hsaBalance":"1000.00"},由Json_encode()函数PHP创建。

【问题讨论】:

标签: java android android-volley


【解决方案1】:

我已经修复了这个错误。 这不是网络问题。

queue.add(getRequest);
queue.start();

应该是

queue.add(getRequest);

所以关键是我们应该删除queue.start()

【讨论】:

  • 谢谢你!
【解决方案2】:

Michael Cheng 是对的,因为当我们调用 newRequestQueue 时,volley 已经启动了 RequestQueue,如下所示:

public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}

当我们调用 start 时,volley 会调用 stop 以“确保所有当前正在运行的调度程序都停止”,在 stop 方法中 volley 执行以下操作:

public void stop() {
    if (mCacheDispatcher != null) {
        mCacheDispatcher.quit();
    }
    for (int i = 0; i < mDispatchers.length; i++) {
        if (mDispatchers[i] != null) {
            mDispatchers[i].quit();
        }
    }
}

而 quit 方法在下面这样做:

 public void quit() {
    mQuit = true;
    interrupt();
}

也许你可以看到原因,为什么被打断了。
更多,中断方法如下:

public void interrupt() {
    // Interrupt this thread before running actions so that other
    // threads that observe the interrupt as a result of an action
    // will see that this thread is in the interrupted state.
    nativeInterrupt();

    synchronized (interruptActions) {
        for (int i = interruptActions.size() - 1; i >= 0; i--) {
            interruptActions.get(i).run();
        }
    }
}

原因可能如上所述:

在运行动作之前中断这个线程,以便其他观察到作为一个动作结果的中断的线程将看到这个线程处于中断状态。

【讨论】:

  • 这是有道理的,@xiaoyee。在这里遇到间歇性问题。感谢您的帮助。
【解决方案3】:

您的连接有时会出现问题。看InterruptedIOExceptionAPI:

InterruptedIOException 表示 I/O 操作已被中断。抛出 InterruptedIOException 以指示输入或输出传输已终止,因为执行它的线程被中断。

所以只有你能做的就是捕捉转换 JSon 时可能发生的异常并为此提供解决方法。

// rest of your code...

final String url = "https://www.myserver.com/api/getBalanceInfoTest?token=7ff3317a4f3dc07d0c297a7d16d2049c&t=" + System.currentTimeMillis();

try {
    JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,

    // rest of your code...

    queue.add(getRequest);
    queue.start();
} catch (InterruptedIOException e) {
    // do something when fail print error, show a toast
    System.out.err("Error, connection interrupted" + e.getMessage());
    Toast.makeText(getApplicationContext(), "press button again",  Toast.LENGTH_LONG).show();
} 

【讨论】:

    猜你喜欢
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2014-02-12
    相关资源
    最近更新 更多