首页 > 解决方案 > 如何使用 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;
}

有没有更好/更新的方法来实现我想要做的事情?

标签: javaandroidjsonvalidationauthentication

解决方案


推荐阅读