注册时,我无法获得响应代码和错误消息,所以您可以帮我吗?
这是我的界面
public interface SignupAPI {
@FormUrlEncoded
@POST("users")
Call<ResponseBody> createUser(
@Field("email") String email,
@Field("password") String password,
@Field("role") String role
);
}
这是Java类
public class SignupClient {
private static final String BASE_URL = "http://74.207.233.160/api/v1/";
private static SignupClient mInstance;
private Retrofit retrofit;
private SignupClient(){
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
}
public static synchronized SignupClient getmInstance(){
if (mInstance == null){
mInstance = new SignupClient();
}
return mInstance;
}
public SignupAPI getApi(){
return retrofit.create(SignupAPI.class);
}
}
这是注册活动
progressBar.setVisibility(View.VISIBLE);
Call<ResponseBody> call = SignupClient.getmInstance().getApi().createUser(email, password,role);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()){
progressBar.setVisibility(View.GONE);
Toast.makeText(SignupActivity.this, "Account Sucessfully Created", Toast.LENGTH_SHORT).show();
}else {
try {
progressBar.setVisibility(View.GONE);
JSONObject jsonError = new JSONObject(response.errorBody().string());
Toast.makeText(SignupActivity.this, jsonError.getString("errors"),Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
progressBar.setVisibility(View.GONE);
e.printStackTrace();
} catch (IOException e) {
progressBar.setVisibility(View.GONE);
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(SignupActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
我无法同时收到错误消息和响应代码,所以请帮助我。
这里是邮递员PostMan API
答案 0 :(得分:0)
在这里,我写了如何从成功响应和错误响应中获取HTTP代码。
@Override
public void onResponse(Call<T> call, Response<T> response) {
int statusCode = response.code();
}
@Override
public void onFailure(Call<T> call, Throwable t) {
if (new Exception(t) instanceof HttpException) {
int statusCode = ((HttpException) t).getStatusCode();
else {
// unknown error
}
}