任何人都可以通过输入用户名和密码来帮助获得响应吗



我是android开发的新手。因此,当我点击提交按钮时,plz帮助在代码中添加http以获得响应。我已经完成了用户名和密码的所有验证。但我不知道如何在这段代码中使用JSONRESTFUL。所以请帮我解决这个问题。

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.Button;
    import android.widget.EditText;
 public class MainActivity extends Activity {

 private static final String SERVICE_URI = "http://www.safepestadmin.com.au/windex.php?itfpage=login";
    public  EditText edittext_username, edittext_password;
Button button_submit;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);  

    edittext_password = (EditText) findViewById(R.id.login_edittext_password);
    edittext_username = (EditText) findViewById(R.id.login_edittext_username);
    button_submit = (Button) findViewById(R.id.login_button_submit);


    button_submit.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
               String email = edittext_username.getText().toString().trim();
               String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\.+[a-z]+";
               String pwd = edittext_password.getText().toString();

               if (email.matches("")   && pwd.matches(""))
               {
                   Toast.makeText(getApplicationContext(), "Please enter a username and a password", Toast.LENGTH_SHORT).show();
               }
               else if (email.matches(emailPattern)    && pwd.matches(""))
                   {
                   Toast.makeText(getApplicationContext(),"Please enter a password",Toast.LENGTH_SHORT).show();
                   }
                  else if (email.matches("") && pwd.length()>0) 
                  {
                  Toast.makeText(getApplicationContext(),"Please enter a username", Toast.LENGTH_SHORT).show();
                  }         
                  else if (!email.matches(emailPattern) && pwd.length()>0) {
                      Toast.makeText(getApplicationContext(), "Invalid email address", Toast.LENGTH_SHORT).show();
                  }
                  else if (!email.matches(emailPattern)  && pwd.matches("")) {
                      Toast.makeText(getApplicationContext(), "Please enter a password", Toast.LENGTH_SHORT).show();
                  }
                  else if (email.matches("alam@gmail.com") && pwd.matches("12345")) {
                      Toast.makeText(getApplicationContext(), "Successfully Logged In", Toast.LENGTH_LONG).show();
                  }
                  else {
                      Toast.makeText(getApplicationContext(), "Please enter registered email and password", Toast.LENGTH_LONG).show();
                  }
        }       
    });
}
   }

你可以试试这个:

  • 将您的密码和用户名发送到服务器
  • 在服务器中,在数据库中保持密码加密
  • 当用户名和密码进入Web服务时,您可以获取用户密码并对其进行解密,然后与来自客户端的密码进行比较
  • 如果密码匹配,您可以向客户端发送true如果错误,您可以发送false
  • 在客户端中,如果来自Web服务的true,您可以授予进入人员的权限

客户端代码:

您可以创建这样的类:

public class web_api_get  extends AsyncTask<Object, Object, String> {
     @Override
    public String doInBackground(Object... params) {
        StringBuilder builder = new StringBuilder();
        HttpParams params2 = new BasicHttpParams();
        HttpProtocolParams.setVersion(params2, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params2, "UTF-8");
        params2.setBooleanParameter("http.protocol.expect-continue", false);

        HttpClient client = new DefaultHttpClient(params2); 
        HttpGet httpGet = new HttpGet(params[0]+""); 
        try {       
          HttpResponse response = client.execute(httpGet);
          StatusLine statusLine = response.getStatusLine(); 
          int statusCode = statusLine.getStatusCode();
          if (statusCode == 200) {  
             HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
              builder.append(line);
            }
          } else {
           // Log.e(ParseJSON.class.toString(), "Failed to download file");
          } 
            } catch (Exception e) { 
            }
        return builder.toString(); 
    } 
}

然后你可以这样称呼它:

字符串结果=new web_api_get().execute("此处的链接包括您的密码和用户名").get();

然后result从Web服务

获取truefalse

尝试在AsyncTask类中执行这段代码。

@Override
protected Integer doInBackground(Context... params) {
// TODO Auto-generated method stub
try {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(("http://URL/Login_Auth? Username="+username+"").replace(" ","%20"));
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity =response.getEntity();
    String responseData = EntityUtils.toString(entity);
            Log.d("====Response====",""+responseData.toString());
    }
    }

在Log.d()中,您可以从URL获取响应。

使用aysctask并将用户名和密码发送到服务器。使用此代码并在单击登录按钮后调用此asytask

 private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
        ProgressDialog mProgressDialog;
        @Override
        protected void onPostExecute(Void result) {
            mProgressDialog.dismiss();
        }
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(MainActivity.this, "Loading...", "Data is Loading...");
        }
        @Override
        protected Void doInBackground(Void... params) {
            //Create new default HTTPClient
            httpclient = new DefaultHttpClient();
            //Create new HTTP POST with URL to php file as parameter
            httppost = new HttpPost("http://10.0.2.2/myteamapp/index.php"); 
            //Assign input text to strings
            username = etUser.getText().toString();
            password = etPass.getText().toString();

            //Next block of code needs to be surrounded by try/catch block for it to work
            try {
                //Create new Array List
                nameValuePairs = new ArrayList<NameValuePair>(2);
                //place them in an array list
                nameValuePairs.add(new BasicNameValuePair("user", "username"));
                nameValuePairs.add(new BasicNameValuePair("pass", "password"));
                //Add array list to http post
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                //assign executed form container to response
                response = httpclient.execute(httppost); //response from the PHP file
                //check status code, need to check status code 200
                if(response.getStatusLine().getStatusCode() == 200){
                    //assign response entity to http entity
                    entity = response.getEntity();
                    //check if entity is not null
                    if(entity != null){

                        //Create new input stream with received data assigned
                        InputStream instream = entity.getContent();
                        //Create new JSON Object. assign converted data as parameter.
                        JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
                        //assign json responses to local strings
                        String retUser = jsonResponse.getString("user");//mySQL table field
                        String retPass = jsonResponse.getString("pass");
                        //Validate login
                        if(username.equals(retUser)&& password.equals(retPass)){ //Check whether 'retUser' and 'retPass' matches username/password 
                            //Display a Toast saying login was a success
                            Toast.makeText(getBaseContext(), "Successful", Toast.LENGTH_SHORT).show();

                        } else {
                            //Display a Toast saying it failed.
                            Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
                        }
                    }

                }

            } catch(Exception e){
               // e.printStackTrace();
                //Display toast when there is a connection error
                //Change message to something more friendly
               Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
               Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();
               return null;
            }

            return null;
        }
    }
}

最新更新