当状态码为 400 时,volley 返回空响应

时间:2021-06-09 05:48:01

标签: java android android-volley

我正在尝试将数据发布到 android 中的 API,它在邮递员中成功地使用了这个 body raw:

{
    "phonenumber": "12345",
    "username": "test",
    "password": "1234",
    "roles": 1
}

成功的响应是:

{
    "message": "Registered successfully!"
}

错误的响应是:

{
    "message": "Failed! this user already registered!"
}

所以在android中,我首先尝试了改造库,如果我尝试注册的用户不存在并且我得到正确的响应,则该帖子可以完美运行 但如果用户存在,则响应返回 null 400 状态代码

所以我尝试使用 volley 来解决问题,但得到了相同的结果 这是我的代码:

private void userSignUp(){

        //defining a progress dialog to show while signing up
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Signing Up...");
        progressDialog.show();

        String phonenumber = editTextPhonenumber.getText().toString().trim();
        String username = editTextUsername.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        // url to post our data
        String url = "http://xxxx/api/auth/signup";

        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(SignUpActivity.this);

        JSONObject object = new JSONObject();
        try {
            //input your API parameters
            object.put("phonenumber", phonenumber);
            object.put("username", username);
            object.put("password", password);
            object.put("roles", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, object,
                new com.android.volley.Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Toast.makeText(getApplicationContext(), "String Response : "+ response.toString(), Toast.LENGTH_LONG).show();
                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), "String Response : "+ error.networkResponse.statusCode + "\nResponse Data " + error.networkResponse.data
                        + "\nCause " + error.getCause()
                        + "\nmessage" + error.getMessage(), Toast.LENGTH_LONG).show();
            }

        }){
            @Override
            public String getBodyContentType() {
                return "application/json";
            }
        };

        queue.add(jsonObjectRequest);
}

这是改造版本:

private void userSignUp(){

        //defining a progress dialog to show while signing up
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Signing Up...");
        progressDialog.show();

        String phonenumber = editTextPhonenumber.getText().toString().trim();
        String username = editTextUsername.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        //building retrofit object
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(APIUrl.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        //Defining retrofit api service
        APIService service = retrofit.create(APIService.class);

        //Defining the user object as we need to pass it with the call
        User user = new User(phonenumber, username, password, 1);

        //defining the call
        Call<Result> call = service.createUser(user);

        //calling the api
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                //hiding progress dialog
                progressDialog.dismiss();
                if(response.isSuccessful()) {
                    Log.d("TAG", "onResponse: " + response.body() + "    " + response.errorBody());
                }


                //displaying the message from the response as toast
                Toast.makeText(getApplicationContext(), response.body().getMessage(), Toast.LENGTH_LONG).show();

                //if there is no error
                if (response.body().getMessage() == "User was registered successfully!") {
                    Toast.makeText(getApplicationContext(), "response.body().getMessage()", Toast.LENGTH_LONG).show();
                    //starting profile activity
                    finish();
                    SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
                    startActivity(new Intent(getApplicationContext(), MainActivity.class));
                }
                else {

                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

使用它的 apiservice:

public interface APIService {
    //The register call
    @POST("auth/signup")
    Call<Result> createUser(@Body User user);
}

请求 pojo:


public class User {
    @SerializedName("id")
    private int id;

    @SerializedName("phonenumber")
    private String phonenumber;

    @SerializedName("username")
    private String username;

    @SerializedName("password")
    private String password;

    @SerializedName("roles")
    private int roles;

    public User(String phonenumber, String username, String password, int roles) {
        this.phonenumber = phonenumber;
        this.username = username;
        this.password = password;
        this.roles = roles;
    }

    public User(int id, String phonenumber, String username, int roles){
        this.id = id;
        this.phonenumber = phonenumber;
        this.username = username;
        this.roles = roles;
    }

    public User(int id, String phonenumber, String username, String password, int roles) {
        this.id = id;
        this.phonenumber = phonenumber;
        this.username = username;
        this.password = password;
        this.roles = roles;
    }

    public int getId() {
        return id;
    }

    public String getPhonenumber() {
        return phonenumber;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword(){
        return password;
    }

    public int getRoles() {
        return roles;
    }
}

响应pojo:

public class Result {
    @SerializedName("message")
    private String message;

    public Result(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

}

有人可以帮我吗?如果用户已经注册,为什么会出现此错误? 如何像成功响应一样显示错误 {"message": "Failed! this user already registered!"} 本身?

1 个答案:

答案 0 :(得分:0)

实际上状态代码“400”不是错误代码,因此,您可以为此创建处理。我不知道它是否适合你,但根据你的帖子,我认为这只是你处理回复的方式。希望能帮到你 :D

例如:

call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, retrofit2.Response<Result> response) {
                mProgressDialog.dismiss();
                if (response.isSuccessful()){
                    try {
                        if(response.body()!=null) {
               Toast.makeText(SignUpActivity.this, "Welcome to our Apps", Toast.LENGTH_LONG).show();
                        } else if (response.errorBody() != null && response.code() == 400){
                           Toast.makeText(SignUpActivity.this, response.body(), Toast.LENGTH_LONG).show();
                        } else {
                            // If you want to add other handler
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                } else {
                    showCustomDialog2(response.errorBody().toString());
                    Toast.makeText(SignUpActivity.this, response.errorBody().toString(), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                Log.e("ERROR : ", t.getMessage());
                mProgressDialog.dismiss();
            }
        });

但是,如果您有权编辑服务器端,我建议您为状态代码添加一个新字段,以便您的应用程序更容易检查您的用户数据,以便您的响应 JSON 看起来像这样:

{
    "status": "400",
    "message": "Failed to sign up, user already exist !!"
}