我正在学习使用Retrofit来在swaggerhub中注册和登录API的REST,但是我无法做到这一点,并且在我的工作室中未显示任何错误消息。我有google REST AUTHENTICATRION,但其中的链接都没有帮助。我也查看了here和here,但仍然不明白。
这里是我的SignUpActivity
public class SignUpActivity extends AppCompatActivity implements View.OnClickListener {
private EditText mPassword;
private EditText mPassword2;
private String password;
private CountryCodePicker ccp;
private ProgressDialog pDialog;
private ProgressBar progressBar;
LoginServices loginService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up_activity);
findViewById(R.id.sign_up_button).setOnClickListener(this);
mPassword = findViewById(R.id.password);
mPassword2 = findViewById(R.id.password2);
progressBar = findViewById(R.id.login_progress);
loginService = ServiceGenerator.createService(LoginServices.class,
getApplication(), USER_BASE_URL);
ccp = findViewById(R.id.ccp);
EditText mUsername = findViewById(R.id.username);
ccp.registerCarrierNumberEditText(mUsername);
}
private boolean validateForm() {
boolean valid = true;
View focusView = null;
password = mPassword.getText().toString();
// String conPassword = mConfirmPasswordView.getText().toString();
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPassword.setError(getString(R.string.error_invalid_password));
focusView = mPassword;
valid = false;
} else {
mPassword.setError(null);
}
if (!valid) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
}
return valid;
}
private boolean isPasswordValid(String password) {
String password2 = mPassword2.getText().toString();
// Add regex for at least 8 characters including lower case, upper case, digit and special character
return password.equals(password2) && password.length() >= 6;
}
private void submitUserDetails( String email, String password){
startUi();
Call<Message> call = loginService.createUser(email, password);
call.enqueue(new Callback<Message>() {
@Override
public void onResponse(Call<Message> call, Response<Message> response) {
if (response.isSuccessful()){
// hidepDialog();
stopUi();
if (response.body() != null){
Message message = response.body();
String regMessage = message.getEmail();
Log.d("GET INFORMATION: ", call.toString());
Log.d("GET MESSAGE: ", message.toString());
Toast.makeText(getApplicationContext(), regMessage + "registered successfully", Toast.LENGTH_SHORT)
.show();
Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}else {
// hidepDialog();
stopUi();
Toast.makeText(getApplicationContext(), "error signup user", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public void onFailure(Call<Message> call, Throwable t) {
stopUi();
Toast.makeText(getApplicationContext(), "error registering user "
+ t.getMessage(), Toast.LENGTH_SHORT)
.show();
}
});
}
private void startUi(){
progressBar.setVisibility(View.VISIBLE);
}
private void stopUi(){
progressBar.setVisibility(View.INVISIBLE);
}
@Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.sign_up_button)
if (validateForm()) {
submitUserDetails(ccp.getDefaultCountryCodeWithPlus(), password);
}
}
}
LoginServices
public interface LoginServices {
@FormUrlEncoded
@POST(Routes.CREATE_USER)
Call<Message> createUser(@Field("email") String email, @Field("password") String password);
@FormUrlEncoded
@POST(Routes.USER_LOGIN)
Call<LoginUser> userLogin(@Field("email") String email, @Field("password") String password);
}
LoginActivity
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private ProgressDialog pDialog;
private ProgressBar progressBar;
private EditText mEtUsername, mEtPassword;
private String username, password;
LoginServices loginService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
progressBar = findViewById(R.id.login_progress);
mEtUsername = findViewById(R.id.et_login_username);
mEtPassword = findViewById(R.id.et_login_password);
findViewById(R.id.btn_login).setOnClickListener(this);
findViewById(R.id.btn_login_register).setOnClickListener(this);
loginService = ServiceGenerator.createService(LoginServices.class, getApplication(), USER_BASE_URL);
}
private boolean validateForm() {
boolean valid = true;
View focusView = null;
username = mEtUsername.getText().toString();
password = mEtPassword.getText().toString();
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mEtPassword.setError(getString(R.string.error_invalid_password));
focusView = mEtPassword;
valid = false;
} else {
mEtPassword.setError(null);
}
// Check for a valid phone number
if (TextUtils.isEmpty(username)) {
mEtUsername.setError("phone number is empty");
focusView = mEtUsername;
valid = false;
} else {
mEtUsername.setError(null);
}
if (!valid) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
}
return valid;
}
private boolean isPasswordValid(String password) {
// Add regex for at least 8 characters including lower case, upper case, digit and special character
return password.length() >= 6;
}
private void login(String email, final String password){
startUi();
Call<LoginUser> call = loginService.userLogin(email, password);
call.enqueue(new Callback<LoginUser>() {
@Override
public void onResponse(Call<LoginUser> call, Response<LoginUser> response) {
if (response.isSuccessful()){
stopUi();
if (response.body() != null){
LoginUser message = response.body();
String email = message.getEmail();
String password1 = message.getPassword();
if (password.equals(password1)){
PrefManager.saveEmail(email, getApplicationContext());
PrefManager.saveUsername(username, getApplicationContext());
Toast.makeText(getApplicationContext(), "user authenticated successfully "
+ email, Toast.LENGTH_SHORT)
.show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}else{
Toast.makeText(getApplicationContext(), "Invalid username or password "
+ email, Toast.LENGTH_SHORT)
.show();
}
}
}else {
stopUi();
Toast.makeText(getApplicationContext(), "error login user", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public void onFailure(Call<LoginUser> call, Throwable t) {
stopUi();
Toast.makeText(getApplicationContext(), "error registering user " + t.getMessage(), Toast.LENGTH_SHORT)
.show();
}
});
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_login:
if (validateForm()){
login(username, password);
}
break;
case R.id.btn_login_register:
startActivity(new Intent(LoginActivity.this,
SignUpActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
break;
}
}
private void startUi(){
progressBar.setVisibility(View.VISIBLE);
}
private void stopUi(){
progressBar.setVisibility(View.INVISIBLE);
}
}
ServiceGenerator
public class ServiceGenerator {
public static <S> S createService(Class<S> serviceClass, Context context, String baseUrl) {
baseUrl = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/";
String token = "";
Gson gson = new GsonBuilder()
.enableComplexMapKeySerialization()
.serializeNulls()
.setDateFormat(DateFormat.LONG)
.setPrettyPrinting()
.setVersion(1.0)
.create();
Retrofit.Builder builder = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(baseUrl);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.readTimeout(90, TimeUnit.SECONDS)
.connectTimeout(90, TimeUnit.SECONDS)
.writeTimeout(90, TimeUnit.SECONDS)
.cache(null);
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging);
}
/* if(context != null) {
token = PreferenceUtils.getToken(context);
}
if (token != null) {
AuthenticationInterceptor authenticationInterceptor =
new AuthenticationInterceptor(token);
httpClient.addInterceptor(authenticationInterceptor);
}else {
}*/
builder.client(httpClient.build());
Retrofit retrofit = builder.build();
return retrofit.create(serviceClass);
}
}
恒定
public interface Constant {
String AUTHORIZATION = "AUTHORIZATION";
String TOKEN = "token";
String USER_BASE_URL = "https://192.*********/";
String KEY_USERNAME = "username";
String KEY_EMAIL = "email";
String KEY_NAME = "name";
}
型号
public class LoginUser {
@SerializedName("email")
@Expose
private String email;
@SerializedName("password")
@Expose
private String password;
/**
* No args constructor for use in serialization
*/
public LoginUser() {
}
public LoginUser(String email, String password){
this.email = email;
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public class Message {
@SerializedName("email")
@Expose
private String email;
@SerializedName("password")
@Expose
private String password;
/**
* No args constructor for use in serialization
*/
public Message() {
}
public Message(String email, String password) {
this.email = email;
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
谢谢。