我正在使用RxJava进行改造。我想知道如何在请求失败或成功时检索请求发送的BODY / RAW。
这是我的控制器调用API:
ChatMessage body = new ChatMessage();
...
//configuration of body variable is omitted.
...
chatController.sendMessage(body).subscribe(this::onSendMessageSuccess, this::onSendMessageError);
这些是获得答案的方法:
private void onSendMessageSuccess(ChatRestResponse response) {
// How can I get the "ChatMessage body" sent in at first by the re
}
private void onSendMessageError(Throwable throwable) {
// How can I get the "ChatMessage body" sent in at first by the request
}
我想知道如何获取用于发出请求的ChatMessage类。
仅供参考
这是我的界面:
@Headers({
"Accept: application/json",
"Content-Type: application/json"
})
@POST(URL)
Observable<ChatRestResponse> sendMessage(
@Header("Authorization") String token,
@Body ChatMessage body);
这是我的控制器,它调用api:
public Observable<ChatRestResponse> sendMessage(ChatMessage body) {
String accessToken = mPref.getAccesToken();
return mChatApi.sendMessage(accessToken , body)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
}
答案 0 :(得分:1)
Brother On Failure没有任何机构存在回应。只会有一些代码与它所面临的错误相关联。像404等
但是,如果您正在谈论自己的服务器响应失败。就像您通过Retrofit从您的应用程序登录到您的帐户一样。如果您输入了错误的凭据,互联网和与服务器的连接都可以,即使这样,响应也将运行函数onResponce()
。但是在这里,您可以检查服务器将发送的与类型或错误相关联的服务器内部错误。
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (response.code == HttpURLConnection.HTTP_OK) {
//All is well
// you can get body here as
String token = responce.body().getToken();
//etc
} else {
//Something went wrong like password etc
//You can check the body here also in case of failure
//Which is due to some internal server error
//because of wrong credentials
//But this response is in failure and also have a body
//I guess this is what u want
String failuerToken = responce.getBody().getAccessToken();
new AlertDialog.Builder(LoginActivity.this)
.setMessage("Invalid Credentials")
.setCancelable(false)
.setPositiveButton("Try Again", null)
.show();
}
}
@Override
public void onFailure(Call call, Throwable t) {
showProgress(false);
new AlertDialog.Builder(LoginActivity.this)
.setMessage("Unable to reach server")
.setCancelable(false)
.setPositiveButton("Try Again", null)
.show();
call.cancel();
}
});
请注意
LoginResponse
是我自己的班级
public class LoginResponse {
@SerializedName("access_token")
@Expose
public String accessToken;
@SerializedName("token_type")
@Expose
public String tokenType;
@SerializedName("expires_in")
@Expose
public Integer expiresIn;
}
<强>更新强>
Call<LoginResponse> call = apiInterface.Login(requestData);
请参阅我使用requestData
发送数据。解决问题的唯一方法是创建一个单独的包名urils
,创建一个类RequestData
并在其中放入一些静态变量。
public class RequestData {
public static String username;
public static String password;
public static String email;
public static Int age;
//etc
}
像这样设置变量值
RequestData.username = "abcd";
RequestData.password = "abcd";
RequestData.email = "abcd@email.com";
RequestData.age = 20";
然后通过api call
发送数据。
失败后,使用此类从中访问以前的数据并分别在UI上显示。