android使用post方法登录,使用REST API使用POST方法在Android中登录示例

如果您熟悉库,则完成此任务的简单方法是使用库.我推荐

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解析出现问题,它将阻止应用程序崩溃.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值