这是我的登录API,我想登录该应用程序。
private void attemptLogin(final String email,final String password) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BaseUrl)
.build();
LoginApi service = retrofit.create(LoginApi.class);
final User user = new User();
user.setEmail(email);
user.setPassword(password);
final Call<List<User>> userCall = service.login(email,password);
userCall.enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intent);
}
@Override
public void onFailure(Call<List<User>> call, Throwable t) {
Toast.makeText(MainActivity.this, " Fail to login ", Toast.LENGTH_SHORT).show();
}
});
}
}
http://192.168.1.14/shop/api2/login.php?email=xxxxxx@gmail.com&password=xxxxxx
答案 0 :(得分:1)
在 build.gradle
文件中添加以下行:
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
为api params创建一个公共接口:
例如。 @POST("api/auth")
Call<Auth> auth(@Field("username") String username, @Field("password") String password);
private void executeAuthEndpoint() {
String _loginId = loginId.getText().toString();
String _password = password.getText().toString();
if (_loginId.length() > 0 && _password.length() > 0) {
endpoint.auth(_loginId, _password).enqueue(new Callback<Auth>() {
@Override
public void onResponse(Call<Auth> call, Response<Auth> response) {
if (response.isSuccessful() && response.body() != null && response.body().getStatus().equalsIgnoreCase("success")) {
// your code
}
else if (response.body()!=null && response.body().getMessage()!=null) {
Toast.makeText(getActivity(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), R.string.message_auth_fail, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<Auth> call, Throwable t) {
if (call.isExecuted()) return;
ErrorHandler.handleError(getActivity(), t);
}
});
} else {
Toast.makeText(getActivity(), R.string.message_empty_field, Toast.LENGTH_SHORT).show();
}
}