我正在使用来自loopj的出色的异步http库,但是遇到了一个小障碍。

如果用户没有互联网连接或失去了连接,则该应用程序将不会返回任何内容。这部分是预期的,但也不会触发onFailure方法。

另外,我在连接互联网时使用的代码也可以正常工作,因此服务器端没有问题。

这是一些简化到最低限度的代码。它也不起作用(我也对此进行了测试)

String url = getString(R.string.baseurl) + "/appconnect.php";
client.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
client.get(url, null, new JsonHttpResponseHandler()
{
    @Override
    public void onSuccess(JSONArray response)
    {
        Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(Throwable e, JSONArray errorResponse)
    {
        Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
    }
});

谢谢,
阿什利

最佳答案

您可以尝试以下方法:

AsyncHttpRequest->makeRequestWithRetries()中,将捕获添加到SocketException中,如下所示:

while (retry) {
        try {
            makeRequest();
            return;
        } catch (UnknownHostException e) {
            if(responseHandler != null) {
                responseHandler.sendFailureMessage(e, "can't resolve host");
            }
            return;
        } catch (SocketException e){
            // Added to detect no connection.
            if(responseHandler != null) {
                responseHandler.sendFailureMessage(e, "can't resolve host");
            }
            return;
        } catch (IOException e) {
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        } catch (NullPointerException e) {
            // there's a bug in HttpClient 4.0.x that on some occasions causes
            // DefaultRequestExecutor to throw an NPE, see
            // http://code.google.com/p/android/issues/detail?id=5255
            cause = new IOException("NPE in HttpClient" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        }
    }

关于java - Loopj Android异步Http-未触发onFailure,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12866353/

10-08 23:52