username = requestUser;
if (password == null)
if (requestPassword != null)
password = requestPassword;
RequestCallback handler = new RequestCallback() {
public void onResponseReceived(Request request, Response response) {
try {
String resp = response.getText();
if (resp.equals(""))
throw new RuntimeException("empty");
HashMap reply = (HashMap) decode(resp);
if (reply == null) {
RuntimeException runtimeException = new RuntimeException(
"parse: " + response.getText());
fireFailure(runtimeException);
callback.onFailure(runtimeException);
}
if (isErrorResponse(reply)) {
RuntimeException runtimeException = new RuntimeException(
"error: " + reply.get("error"));
fireFailure(runtimeException);
callback.onFailure(runtimeException);
} else if (isSuccessfulResponse(reply)) {
callback.onSuccess(reply.get("result"));
} else {
RuntimeException runtimeException = new RuntimeException(
"syntax: " + response.getText());
fireFailure(runtimeException);
callback.onFailure(runtimeException);
}
} catch (RuntimeException e) {
fireFailure(e);
callback.onFailure(e);
} finally {
decreaseRequestCounter();
}
}
public void onError(Request request, Throwable exception) {
try {
if (exception instanceof RequestTimeoutException) {
RuntimeException runtimeException = new RuntimeException(
"timeout");
fireFailure(runtimeException);
callback.onFailure(runtimeException);
} else {
RuntimeException runtimeException = new RuntimeException(
"other");
fireFailure(runtimeException);
callback.onFailure(runtimeException);
}
} catch (RuntimeException e) {
fireFailure(e);
callback.onFailure(e);
} finally {
decreaseRequestCounter();
}
}
private boolean isErrorResponse(HashMap response) {
return response.get("error") != null
&& response.get("result") == null;
}
private boolean isSuccessfulResponse(HashMap response) {
return response.get("error") == null
&& response.containsKey("result");
}
};
increaseRequestCounter();
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
if (requestTimeout > 0)
builder.setTimeoutMillis(requestTimeout);
builder.setHeader("Content-Type", "application/json; charset=utf-8");
String body = new String(encode(request));
builder.setHeader("Content-Length", Integer.toString(body.length()));
if (requestCookie != null)
if (Cookies.getCookie(requestCookie) != null)
builder.setHeader("X-Cookie", Cookies.getCookie(requestCookie));
if (username != null)
builder.setUser(username);
if (password != null)
builder.setPassword(password);
try {
builder.sendRequest(body, handler);
} catch (RequestException exception) {
handler.onError(null, exception);
}
}