Я успешно создал API входа с использованием laravel паспорта.
{
"status": "success",
"data": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiZjdmODQ3MzZjMjFkOWQ2..."
}
}
Я создал мобильное приложение с использованием android studio, я создаю интерфейс входа
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface LoginInterface {
String LOGINURL = "http://MYIP/AnnocesPFE/public/api/";
@FormUrlEncoded
@POST("login")
Call<String> getUserLogin(
@Field("email") String email,
@Field("password") String password
);
}
Login_Fragment
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.text.InputType;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public class Login_Fragment extends Fragment implements View.OnClickListener {
private static View view;
private static EditText emailid, password;
private static Button loginButton;
private static TextView signUp;
private static CheckBox show_hide_password;
private static LinearLayout loginLayout;
private static Animation shakeAnimation;
private static FragmentManager fragmentManager;
public Login_Fragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.login_layout, container, false);
initViews();
setListeners();
return view;
}
// Initiate Views
private void initViews() {
fragmentManager = getActivity().getSupportFragmentManager();
emailid = (EditText) view.findViewById(R.id.login_emailid);
password = (EditText) view.findViewById(R.id.login_password);
loginButton = (Button) view.findViewById(R.id.loginBtn);
signUp = (TextView) view.findViewById(R.id.createAccount);
show_hide_password = (CheckBox) view
.findViewById(R.id.show_hide_password);
loginLayout = (LinearLayout) view.findViewById(R.id.login_layout);
// Load ShakeAnimation
shakeAnimation = AnimationUtils.loadAnimation(getActivity(),
R.anim.shake);
// Setting text selector over textviews
XmlResourceParser xrp = getResources().getXml(R.drawable.text_selector);
try {
ColorStateList csl = ColorStateList.createFromXml(getResources(),
xrp);
show_hide_password.setTextColor(csl);
signUp.setTextColor(csl);
} catch (Exception e) {
}
}
// Set Listeners
private void setListeners() {
loginButton.setOnClickListener(this);
signUp.setOnClickListener(this);
// Set check listener over checkbox for showing and hiding password
show_hide_password
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton button,
boolean isChecked) {
// If it is checkec then show password else hide
// password
if (isChecked) {
show_hide_password.setText(R.string.hide_pwd);// change
// checkbox
// text
password.setInputType(InputType.TYPE_CLASS_TEXT);
password.setTransformationMethod(HideReturnsTransformationMethod
.getInstance());// show password
} else {
show_hide_password.setText(R.string.show_pwd);// change
// checkbox
// text
password.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
password.setTransformationMethod(PasswordTransformationMethod
.getInstance());// hide password
}
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loginBtn:
checkValidation();
break;
// Replace forgot password fragment with animation
case R.id.createAccount:
// Replace signup frgament with animation
fragmentManager
.beginTransaction()
.setCustomAnimations(R.anim.right_enter, R.anim.left_out)
.replace(R.id.frameContainer, new SignUp_Fragment(),
Utils.SignUp_Fragment).commit();
break;
}
}
// Check Validation before login
private void checkValidation() {
// Get email id and password
String getEmailId = emailid.getText().toString();
String getPassword = password.getText().toString();
// Check patter for email id
Pattern p = Pattern.compile(Utils.regEx);
Matcher m = p.matcher(getEmailId);
// Check for both field is empty or not
if (getEmailId.equals("") || getEmailId.length() == 0
|| getPassword.equals("") || getPassword.length() == 0) {
loginLayout.startAnimation(shakeAnimation);
new CustomToast().Show_Toast(getActivity(), view,
"Enter both credentials.");
}
// Check if email id is valid or not
else if (!m.find())
new CustomToast().Show_Toast(getActivity(), view,
"Your Email is Invalid.");
// Else do login and do your stuff
else {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(LoginInterface.LOGINURL)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
LoginInterface api = retrofit.create(LoginInterface.class);
Call<String> call = api.getUserLogin(getEmailId, getPassword);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Log.i("Responsestring", response.body().toString());
Log.i("onSuccess", response.body().toString());
String jsonresponse = response.body().toString();
try {
JSONObject jsonObject = new JSONObject(jsonresponse);
if (jsonObject.getString("success").equals("true")) {
Toast.makeText(getActivity(), "Login Successfully!", Toast.LENGTH_SHORT)
.show();
Intent intent;
intent = new Intent(getActivity(), activity_list_events.class);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
loginLayout.startAnimation(shakeAnimation);
new CustomToast().Show_Toast(getActivity(), view,
"Your Password is Invalid.");
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(getContext(), "Server invalid \n" + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
}
моя проблема, когда я захожу с действительным адресом электронной почты и паролем, я не могу получить доступ к своему списку активности. Страница заблокирована на странице входа без каких-либо сообщений об ошибках.