我正在开发我的第一个 Android 应用程序,我们有自己的 REST API,网址如下。 “www.abc.com/abc/def/”。对于登录活动,我需要通过传递 3 个参数(标识符、电子邮件和密码)来执行 httppost。然后在获得 http 响应后,我需要显示对话框是否无效凭据或切换到另一个活动。
有人可以向我展示如何执行此操作的示例代码吗?
完成此任务的一个简单方法是使用库(如果您熟悉库)。我推荐 Ion,因为它体积小且易于使用。添加库并将以下代码片段添加到您选择的方法中。
Ion.with(getApplicationContext())
.load("http://www.example.com/abc/def/")
.setBodyParameter("identifier", "foo")
.setBodyParameter("email", "[email protected]")
.setBodyParameter("password", "p@ssw0rd")
.asString()
.setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
// Result
}
});
注意!如果您想进行网络调用,如果您不知道,则必须将以下权限添加到
AndroidManifest.xml
标签之外的 <application>
。
<uses-permission android:name="android.permission.INTERNET" />
要检查登录成功或失败的响应,您可以在
onComplete
方法(其中 // Result
所在的位置)中添加以下代码片段:
try {
JSONObject json = new JSONObject(result); // Converts the string "result" to a JSONObject
String json_result = json.getString("result"); // Get the string "result" inside the Json-object
if (json_result.equalsIgnoreCase("ok")){ // Checks if the "result"-string is equals to "ok"
// Result is "OK"
int customer_id = json.getInt("customer_id"); // Get the int customer_id
String customer_email = json.getString("customer_email"); // I don't need to explain this one, right?
} else {
// Result is NOT "OK"
String error = json.getString("error");
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show(); // This will show the user what went wrong with a toast
Intent to_main = new Intent(getApplicationContext(), MainActivity.class); // New intent to MainActivity
startActivity(to_main); // Starts MainActivity
finish(); // Add this to prevent the user to go back to this activity when pressing the back button after we've opened MainActivity
}
} catch (JSONException e){
// This method will run if something goes wrong with the json, like a typo to the json-key or a broken JSON.
Log.e(TAG, e.getMessage());
Toast.makeText(getApplicationContext(), "Please check your internet connection.", Toast.LENGTH_LONG).show();
}
为什么我们需要 try & catch,首先我们被迫这么做,另一方面,如果 JSON 解析出现问题,它可以防止应用程序崩溃。
这就是您从头开始处理此问题的方法,在您的登录活动中使用此代码块,如果您使用 POST 方法,您将进行一些修改,因为我使用 GET 方法来检查凭据,LoginHandler 扩展了 AsyncTask 因为它是不允许在主线程上进行网络操作...
private class LoginHandler extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
String URL = "url to get from ";
JSONObject jsonReader=null;
try {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(URL));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
jsonReader=new JSONObject(responseString);
} else {
// Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
// TODO Handle problems..
String er=e.getMessage();
} catch (IOException e) {
// TODO Handle problems..
String er=e.getMessage();
}
// Show response on activity
if (!jsonReader.get("UserName").toString().equals("")) {
SharedPreferences sp = getSharedPreferences("LoginInfos", 0);
Editor editor = sp.edit();
editor.putString("email", jsonReader.getString("EmailAddress"));
editor.putString("username", jsonReader.getString("UserName"));
editor.putString("userid", jsonReader.getString("UserId"));
editor.putString("realname", jsonReader.getString("RealName"));
editor.putString("realsurname", jsonReader.getString("RealSurname"));
editor.putString("userprofileimage", jsonReader.getString("UserProfileImage"));
DateFormat dateFormat = new SimpleDateFormat(
"yyyy.MM.dd HH:mm:ss");
// get current date time with Date()
Date date = new Date();
editor.putString("LastLogin",
dateFormat.format(date.getTime()));
editor.commit();
return true;
}
return false;
} catch (Exception ex) {
}
return false;
}
// TODO Auto-generated method stub
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
if (result) {
pdialog.dismiss();
Intent userMainActivityIntent = new Intent(
getApplicationContext(), MainUserActivity.class);
startActivity(userMainActivityIntent);
}
else
{
pdialog.dismiss();
new AlertDialog.Builder(MainActivity.this).setTitle("Login Error")
.setMessage("Email or password is wrong.").setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
} ).show();
}
super.onPostExecute(result);
}
}
binding.buttonLogin.setOnClickListener(view -> {
if (binding.emailInput.getText() == null) {
binding.emailContainer.setError(getResources().getString(R.string.email_username_empty));
} else if (binding.emailInput.getText().toString().trim().length() == 0) {
binding.emailContainer.setError(getResources().getString(R.string.email_username_empty));
} else if (binding.passwordInput.getText() == null) {
binding.passwordContainer.setError(getResources().getString(R.string.password_empty));
} else if (binding.passwordInput.getText().toString().trim().length() == 0) {
binding.passwordContainer.setError(getResources().getString(R.string.password_empty));
} else {
callLogIn(binding.emailInput.getText().toString(), binding.passwordInput.getText().toString());
}
});
private void callLogIn(String email, String password) {
if (AppUtil.isInternetAvailable(Login.this)) {
binding.loader.setVisibility(View.VISIBLE);
JSONObject jsonObject = new JSONObject();
try {
if (Patterns.EMAIL_ADDRESS.matcher(binding.emailInput.getText()).matches())
jsonObject.put("email", email);
else
jsonObject.put("username", email);
jsonObject.put("password", password);
jsonObject.put("device", getResources().getString(R.string.android));
jsonObject.put("fcm_id", Prefs.getPrefInstance().getValue(Login.this, Const.FCM_ID, ""));
} catch (JSONException e) {
binding.loader.setVisibility(View.GONE);
e.printStackTrace();
}
String params = jsonObject.toString();
final RequestBody user_logging_in = RequestBody.create(params, MediaType.parse("application/json"));
APIUtils.getAPIService().user_login(user_logging_in).enqueue(new Callback<LoginUserResponse>() {
@Override
public void onResponse(@NonNull Call<LoginUserResponse> call, @NonNull Response<LoginUserResponse> response) {
if (response.body() != null) {
if (response.body().getStatus() != null && response.body().getStatus().equals(200)) {
Prefs.getPrefInstance().setValue(Login.this, Const.LOGIN_ACCESS, getString(R.string.logged_in));
if (binding.rememberMe.isChecked()) {
Prefs.getPrefInstance().setValue(Login.this, Const.PASSWORD, password);
Prefs.getPrefInstance().setValue(Login.this, Const.USER_NAME_EMAIL_CHECKED, email);
Prefs.getPrefInstance().setValue(Login.this, Const.KEEP_USER_LOGGED_IN, "1");
} else {
Prefs.getPrefInstance().setValue(Login.this, Const.PASSWORD, "");
Prefs.getPrefInstance().setValue(Login.this, Const.USER_NAME_EMAIL_CHECKED, "");
Prefs.getPrefInstance().setValue(Login.this, Const.KEEP_USER_LOGGED_IN, "0");
}
Prefs.getPrefInstance().setValue(Login.this, Const.EMAIL, response.body().getData().get(0).getEmail());
Prefs.getPrefInstance().setValue(Login.this, Const.USER_ID, response.body().getData().get(0).getUserId());
Prefs.getPrefInstance().setValue(Login.this, Const.USER_NAME, response.body().getData().get(0).getUsername());
Prefs.getPrefInstance().setValue(Login.this, Const.PHONE_NUMBER, response.body().getData().get(0).getPhone());
Prefs.getPrefInstance().setValue(Login.this, Const.USER_FULL_NAME, response.body().getData().get(0).getName());
Prefs.getPrefInstance().setValue(Login.this, Const.TOKEN, response.body().getToken());
if (response.body().getData().get(0).getImage() != null && !response.body().getData().get(0).getImage().isEmpty())
Prefs.getPrefInstance().setValue(Login.this, Const.PROFILE_IMAGE, response.body().getData().get(0).getImage());
binding.loader.setVisibility(View.GONE);
AppUtil.show_Snackbar(Login.this, binding.mainContainer, response.body().getMessage(), true);
startActivity(new Intent(Login.this, HomeScreen.class));
} else {
binding.loader.setVisibility(View.GONE);
View dialog_view = LayoutInflater.from(Login.this).inflate(AppUtil.setLanguage(Login.this, R.layout.simple_dialog_text_button), null);
final AlertDialog dialog = new AlertDialog.Builder(Login.this)
.setCancelable(false)
.setView(dialog_view)
.show();
if (dialog.getWindow() != null)
dialog.getWindow().getDecorView().getBackground().setAlpha(0);
((TextView) dialog_view.findViewById(R.id.dialog_text)).setText(response.body().getMessage());
(dialog_view.findViewById(R.id.dialog_ok)).setVisibility(View.GONE);
((Button) dialog_view.findViewById(R.id.dialog_cancel)).setText("OK");
dialog_view.findViewById(R.id.dialog_cancel).setOnClickListener(view -> {
dialog.dismiss();
});
}
} else {
binding.loader.setVisibility(View.GONE);
View dialog_view = LayoutInflater.from(Login.this).inflate(AppUtil.setLanguage(Login.this, R.layout.simple_dialog_text_button), null);
final AlertDialog dialog = new AlertDialog.Builder(Login.this)
.setCancelable(false)
.setView(dialog_view)
.show();
if (dialog.getWindow() != null)
dialog.getWindow().getDecorView().getBackground().setAlpha(0);
((TextView) dialog_view.findViewById(R.id.dialog_text)).setText("Something went wrong! Please try again.");
(dialog_view.findViewById(R.id.dialog_ok)).setVisibility(View.GONE);
((Button) dialog_view.findViewById(R.id.dialog_cancel)).setText("OK");
dialog_view.findViewById(R.id.dialog_cancel).setOnClickListener(view -> {
dialog.dismiss();
});
}
}
@Override
public void onFailure(@NonNull Call<LoginUserResponse> call, @NonNull Throwable t) {
t.printStackTrace();
binding.loader.setVisibility(View.GONE);
View dialog_view = LayoutInflater.from(Login.this).inflate(AppUtil.setLanguage(Login.this, R.layout.simple_dialog_text_button), null);
final AlertDialog dialog = new AlertDialog.Builder(Login.this)
.setCancelable(false)
.setView(dialog_view)
.show();
if (dialog.getWindow() != null)
dialog.getWindow().getDecorView().getBackground().setAlpha(0);
((TextView) dialog_view.findViewById(R.id.dialog_text)).setText("Something went wrong! Please try again.");
(dialog_view.findViewById(R.id.dialog_ok)).setVisibility(View.GONE);
((Button) dialog_view.findViewById(R.id.dialog_cancel)).setText("OK");
dialog_view.findViewById(R.id.dialog_cancel).setOnClickListener(view -> {
dialog.dismiss();
});
}
});
} else {
View dialog_view = LayoutInflater.from(Login.this).inflate(AppUtil.setLanguage(Login.this, R.layout.simple_dialog_text_button), null);
final AlertDialog dialog = new AlertDialog.Builder(Login.this)
.setCancelable(false)
.setView(dialog_view)
.show();
if (dialog.getWindow() != null)
dialog.getWindow().getDecorView().getBackground().setAlpha(0);
((TextView) dialog_view.findViewById(R.id.dialog_text)).setText(getResources().getString(R.string.no_internet_connection));
(dialog_view.findViewById(R.id.dialog_ok)).setVisibility(View.GONE);
((Button) dialog_view.findViewById(R.id.dialog_cancel)).setText("OK");
dialog_view.findViewById(R.id.dialog_cancel).setOnClickListener(view -> {
dialog.dismiss();
});
}
}