如果您熟悉库,则完成此任务的简单方法是使用库.我推荐
Ion,因为它小而且易于使用.添加库并将以下代码段添加到您选择的方法中.
Ion.with(getApplicationContext())
.load("http://www.example.com/abc/def/")
.setBodyParameter("identifier", "foo")
.setBodyParameter("email", "foo@foo.com")
.setBodyParameter("password", "p@ssw0rd")
.asString()
.setCallback(new FutureCallback() {
@Override
public void onCompleted(Exception e, String result) {
// Result
}
});
注意!如果要进行网络呼叫,则必须将以下权限添加到< application>之外的AndroidManifest.xml中.标记,如果你不知道这一点.
要检查成功登录的响应或失败,您可以在onComplete方法中添加以下代码段(//结果所在的位置):
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();
}
为什么我们需要一个尝试& catch,首先我们被迫,另一方面,如果JSON解析出现问题,它将阻止应用程序崩溃.