简体   繁体   中英

Response Code 422 Retrofit

I'm trying to do a simple authentication with my laravel api. But unfortunately in my android studio project, it's returning a response code 422.

Here is my code in my API:

LoginController.php

public function login(Request $request)
    {
       $this->validateLogin($request);

            if ($this->attemptLogin($request)) {
                $user = $this->guard()->user();
                $user->generateToken();

                return response()->json([
                    'data' => $user->toArray(),
                ]);
            }
        return $this->sendFailedLoginResponse($request);
    }

Then here is in my web interface in Android Studio:

BizWebService.java

    @Headers({
            "Content-Type: application/json",
            "Accept: application/json"
    })
    @POST("api/login")
    @FormUrlEncoded
    Call<LoginResponse> login(
            @Field("username") String username,
            @Field("password") String password);

class LoginResponse extends ServiceResponse {
        @SerializedName("message")
        public String message;

        @SerializedName("errors")
        public ArrayList<Email> errors;

        @SerializedName("data")
        public ArrayList<DataItems> data;
    }

    class DataItems {
        @SerializedName("id")
        @Expose
        public int id;

        @SerializedName("username")
        @Expose
        public String username;

        @SerializedName("api_token")
        @Expose
        public String api_token;

        @SerializedName("whoToVote")
        @Expose
        public String whoToVote;

        @SerializedName("created_at")
        @Expose
        public String created_at;

        @SerializedName("updated_at")
        @Expose
        public String updated_at;
    }

    class Email {
        @SerializedName("email")
        @Expose
        public String email;
    }

Module class:

public class Module {

    public static void register(BizApplication application) {
        BizWebService api = createWebService(application);

        new LiveAccountService(api, application);
        new LiveCandidateService(api, application);
        new LiveCriteriaService(api, application);
    }

    private static BizWebService createWebService(BizApplication application) {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new AuthInterceptor(application.getAuth()))
                .connectTimeout(100, TimeUnit.SECONDS)
                .readTimeout(100, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BizApplication.API_ENDPOINT.toString())
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(new Gson()))
                .build();

        BizWebService webService = retrofit.create(BizWebService.class);
        return webService;
    }

    private static class AuthInterceptor implements Interceptor {

        private final Auth auth;

        private AuthInterceptor(Auth auth) {
            this.auth = auth;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            if (auth.hasAuthToken()) {
                request = request
                        .newBuilder()
                        .addHeader("Authorization", "Bearer " + auth.getAuthToken())
                        .build();
            }

            long t1 = System.nanoTime();
            Log.i("Request", String.format("Sending request %s on %s%n%s",
                    request.url(), chain.connection(), request.headers()));

            Response response = chain.proceed(request);

            if (response.isSuccessful()) {
                return response;
            }


            if (response.code() == 401 && auth.hasAuthToken()) {
                auth.setAuthToken(null);
            }

            long t2 = System.nanoTime();
            Log.i("Response", String.format("Received response for %s in %.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers()));


            return response;
        }
    }
}

LiveAccountService.java

public class LiveAccountService extends BaseLiveService {

    private final Auth auth;


    public LiveAccountService(BizWebService api, BizApplication application) {
        super(api, application);

        auth = application.getAuth();
    }


    @Subscribe
    public void loginUserRequest(Account.LoginRequestRequest request) {
        Call<BizWebService.LoginResponse> call = api.login(request.Username, request.Password);
        call.enqueue(new RetrofitCallback<BizWebService.LoginResponse>(BizWebService.LoginResponse.class) {
            @Override
            protected void onResponseSuccess(Call<BizWebService.LoginResponse> t, Response<BizWebService.LoginResponse> response) {

                    if (response.isSuccessful()) {

                        return;
                    } else {
                        Account.LoginRequestResponse response1 = new Account.LoginRequestResponse();
                        response1.setOperationError("Error");
                        bus.post(response1);
                        Log.e("Server Error", Integer.toString(response.code()));
                    }
            }
        });
    }

I tried posting the request in Postman and it works. I don't have an idea where I did wrong. Any help would be appreciated.

I know that this is an old post of mine but I just want to share on how I solved the problem. It's not really THE solution but it helped me either way in solving my problem.

Basically, my core problem was that I could not see the requests and responses that I've been throwing at my web service so I installed a 3rd party library which monitors the requests that I throw and the responses that I receive from the server. It's the HttpLoggingInterceptor. Then I added it as one of the interceptors in my OkHttpClient object in the createWebService method. Right then, I was able to monitor the requests and responses and I was able to send the right and acceptable data to the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM