java - 如何使用 Web API 在 android 应用中验证登录
问题描述
我正在尝试制作一个 Android 应用程序,其中必须使用从 SQL Server 数据库获取详细信息的 Web API 来验证登录凭据。我必须验证登录的方式是,当用户输入“用户名”和“密码”时,“登录”按钮的 onClickmyURL/username/password/1
会命中形式为的 HTTP 请求,该请求会检查验证并返回 JSON 响应,如{"data1":0,"data2":"ok","data3":{"data4": [{"data5":2,"data6":"somedata","data7":"somedata","data8":"someNumber","data9":"","data10":"somedata","data11":somedata}]}}
现在在这里,我对“data2”感兴趣。如果 data2 的响应为“ok”,则表示凭据正确,而响应“Invalid Login”表示凭据不正确。从中获取响应的正确方法是什么data2
?
这是我迄今为止尝试过的 -
MainActivity.java
public class MainActivity extends AppCompatActivity
{
password=(EditText) findViewById(R.id.editText2);
userName=(EditText) findViewById(R.id.editText1);
login=(Button) findViewById(R.id.button1);
//on click of login button
login.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
progressBar.setVisibility(View.VISIBLE);
String s1=userName.getText().toString();
String s2=password.getText().toString();
new ExecuteTask().execute(s1,s2);
}
});
}
class ExecuteTask extends AsyncTask<String, Integer, String>
{
@Override
protected String doInBackground(String... params) {
String res=PostData(params);
return res;
}
@Override
protected void onPostExecute(String result) {
progressBar.setVisibility(View.GONE);
//progess_msz.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), result, 3000).show();
}
}
public String PostData(String[] valuse) {
String s="";
try
{
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("myURL" + userName + "/" + passWord + "/1");
httpPost.setEntity(new UrlEncodedFormEntity(list));
HttpResponse httpResponse= httpClient.execute(httpPost);
HttpEntity httpEntity=httpResponse.getEntity();
s= readResponse(httpResponse);
}
catch(Exception exception) {}
return s;
}
public String readResponse(HttpResponse res) {
InputStream is=null;
String return_text="";
try
{
is=res.getEntity().getContent();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
String line="";
StringBuffer sb=new StringBuffer();
while ((line=bufferedReader.readLine())!=null)
{
sb.append(line);
}
return_text=sb.toString();
} catch (Exception e)
{
}
return return_text;
}
有没有更好/更新的方法来实现我想要做的事情?
解决方案
推荐阅读
- c# - Application Insights Telemetry Client - 如何在 Azure Application Insights 中显示日志条目
- sql - 如何在 Postgresql 中使用逻辑运算符实现多个 if 子句
- amazon-web-services - AWS EBS 额外卷附加到创建 ECS 集群时启动的 EC2 实例
- python - 在 Linux 中编写脚本
- android - 由于 http 信任管理器,应用程序被 Google Play 拒绝
- strapi - 有没有办法在strapi.io的文件上传中保留原始文件名?
- java - Guava 表到带有标题的 CSVPrinter
- powershell - 尽管尝试了 TFM 中的所有内容,PowerShell Select-String 仍不匹配
- javascript - 如何在 React 中使用 `||` 进行内联测试?
- routing - 用户按 F5 时如何更快地刷新组件