8

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

谢谢,阿什利

4

3 回答 3

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);
}
于 2012-10-12T21:33:10.047 回答
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);
        }
    }
于 2012-11-12T21:02:34.713 回答
0

尝试这个:

@Override
protected Object parseResponse(byte[] responseBody) throws JSONException {
    return super.parseResponse(responseBody);
}
于 2014-09-25T02:00:00.427 回答