简体   繁体   中英

Android PHP POST Login

I've tried finding the answers in other posts and avoid posting a duplicate; however, many were using deprecated methods. I am trying to create a login activity which will POST user details to php and receive a jsonEncoded status "Authorized" or "Incorrect User Details" response; I've tested the PHP and it works. When I click on the Login Button it will do this:

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btnLogin:

            String username = Username.getText().toString();
            String password = Password.getText().toString();

            User user = new User(username, password);

            authenticate(user);

            userLocalStore.setUserLoggedIn(true);
            userLocalStore.storeUserData(user);

            break;
    }
}

It contains the User function, which makes it easier for me to pass information.

String username, password;

public User (String username, String password) {
    this.username = username;
    this.password = password;
}

Once the User is constructed, Login will call on the authenticate function:

private void authenticate(User user) {

    ServerRequests serverRequests = new ServerRequests(this);
    serverRequests.fetchUserDataAsyncTask(user, returnedUser);{

        if (returnedUser == null){
            showErrorMessage();
        } else {
            logUserIn();
        }
    };
}

Once the user is authenticated it will log the user in and start a new activity:

private void logUserIn() {
    userLocalStore.setUserLoggedIn(true);
    startActivity(new Intent(this, Map.class));
}

The issue I'm having, is that it doesn't seem to make the call to the php, and I'm not sure where I'm going wrong; I've tried piecing together what others have done, but it's not working. I'd appreciate any help.

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class ServerRequests {

    URL url;
    HttpURLConnection conn;
    ProgressDialog progressDialog;

    public ServerRequests(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setCancelable(false);
        progressDialog.setTitle("Authenticating...");
        progressDialog.setMessage("Please wait...");
    }

    public void fetchUserDataAsyncTask(User user, String returnedUser) {
        progressDialog.show();
        new fetchUserDataAsyncTask(user, returnedUser).execute();
    }

    public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, String> {
        User user;
        String returnedUser;


        public fetchUserDataAsyncTask(User user, String returnedUser) {
            this.user = user;
            this.returnedUser = returnedUser;
        }

        @Override
        protected String doInBackground(Void... params) {

            try {

                url = new URL("www.mysite.com/test.php");

                conn = (HttpURLConnection) url.openConnection();
                String param = "username="+user.username+"&password="+user.password;
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("charset", "UTF-8");
                conn.connect();

                OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
                out.write(param);

               //No code to receive response yet, want to get the POST working first. 

            }
            catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            catch (Exception e) {

            } finally {
                progressDialog.dismiss();
            }

            return returnedUser;
        }
    }
}

try with this..

conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String param = "username="+user.username+"&password="+user.password;
OutputStream out = conn.getOutputStream();
DataOutputStream dataOut = new DataOutputStream(out);
dataOut.writeBytes(param.trim());
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
StringBuilder builder = new StringBuilder();
while((line = reader.readLine()) != null) {
    builder.append(line);
}
reader.close();
System.out.println(builder.toString());

in StringBuilder you will get the output which is returned by the server.

it will submit your parameters to php page..

you should use

  HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

instead of

conn = (HttpURLConnection) url.openConnection();

check That HttpsURLConnection

Do like that.

new Login().execute(name, profilePic);//calling

public class Login extends AsyncTask<String, Integer, Double>{
  String response="";
    @Override
    protected Double doInBackground(String... params) {
        // TODO Auto-generated method stub

        postData(params[0],params[1]);

        return null;
    }




    public void postData(String name,String profilePic) {

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("your_url");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair(Constants.AppId,Constants.Value_AppId ));
            nameValuePairs.add(new BasicNameValuePair(Constants.Tag_profile_name, name));
            nameValuePairs.add(new BasicNameValuePair(Constants.Tag_profile_pic, profilePic));


            httppost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse res = httpclient.execute(httppost);
             InputStream content = res.getEntity().getContent();

              BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
              String s = "";
              while ((s = buffer.readLine()) != null) {
                response += s;
              }
              System.out.println("response from server"+response);


        } catch (ClientProtocolException e) {

            // TODO Auto-generated catch block
        } catch (IOException e) {

            // TODO Auto-generated catch block
        }
    }
}

I hope it will help you...!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM