Loopj Android Async Http - onFailure没有被解雇

时间:2012-10-12 20:08:25

标签: java android http asynchronous loopj

我正在使用来自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();
    }
});

谢谢, 阿什利

3 个答案:

答案 0 :(得分:7)

是的,不幸的是,loopj Android库设计得不是很好。如果您实施其他 onFailure回调,其中一个应该触发:

@Override
public void onFailure(Throwable e) {
    Log.e(TAG, "OnFailure!", e);
}
@Override
public void onFailure(Throwable e, String response) {
    Log.e(TAG, "OnFailure!", e);
}
@Override
public void onFailure(Throwable e, JSONArray errorResponse) {
    Log.e(TAG, "OnFailure!", e);
}

答案 1 :(得分:7)

你可以试试这个:

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);
        }
    }

答案 2 :(得分:0)

试试这个:

@Override
protected Object parseResponse(byte[] responseBody) throws JSONException {
    return super.parseResponse(responseBody);
}