如何在ANDROID中使用Cookie?

时间:2016-01-20 09:53:23

标签: php android cookies

它是一个登录应用程序,它将询问用户的用户名和密码,然后将此数据发送到服务器上的某个PHP脚本。这部分工作正常。现在我需要的是通过cookie维护这个会话,即使用户关闭了这个应用程序,以便用户保持登录,直到并且除非他手动注销。

以下是此过程的核心代码

public class SignIn extends AppCompatActivity implements View.OnClickListener {

public Button blogin;
public TextView content, error, link_signup;

public EditText uname, pass;




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



    uname = (EditText) findViewById(R.id.uname);
    pass = (EditText) findViewById(R.id.pass);
    content = (TextView) findViewById(R.id.content);
    error = (TextView) findViewById(R.id.error);
    link_signup = (TextView) findViewById(R.id.link_signup);

    blogin = (Button) findViewById(R.id.blogin);

    blogin.setOnClickListener(this);
    link_signup.setOnClickListener(this);

}


public boolean validate() {
    boolean valid = true;

    String email = uname.getText().toString();
    String password = pass.getText().toString();

    if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
        uname.setError("Enter a valid email address");
        error.setTextSize(20);
        error.setTextColor(Color.parseColor("#FFFFFF"));
        error.setBackgroundColor(Color.parseColor("#646464"));
        error.setText("Invalid Username or Password");

        valid = false;
    } else {
        uname.setError(null);
    }

    if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
        pass.setError("Enter a password between 4 and 10 alphanumeric characters");
        error.setTextSize(20);
        error.setTextColor(Color.parseColor("#FFFFFF"));
        error.setBackgroundColor(Color.parseColor("#646464"));
        error.setText("Invalid Username or Password");
        valid = false;
    } else {
        pass.setError(null);
    }

    return valid;
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.blogin:
            validate();
            new JsonTask().execute("https://www.aboutmyclinic.com/test.php", uname.getText().toString(), pass.getText().toString());
            break;
        case R.id.link_signup:
            startActivity(new Intent(this, Register.class));
            break;


    }

}



@Override
protected void onPause() {
    super.onPause();

    uname.setText("");
    pass.setText("");
    error.setText("");
    error.setBackgroundColor(Color.parseColor("#FFFFFF"));
}

public class JsonTask extends AsyncTask<String, String, String> {


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

        HttpURLConnection connection = null;
        BufferedReader reader = null;




        try {

            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();



            connection.setReadTimeout(10000);
            connection.setConnectTimeout(15000);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("firstParam", params[1])
                    .appendQueryParameter("secondParam", params[2]);

            String query = builder.build().getEncodedQuery();
            OutputStream os = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();


            connection.connect();






            InputStream inputStream = connection.getInputStream();
            StringBuffer buffer = new StringBuffer();

            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {

                buffer.append(line + "\n");
            }
            return buffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {

                }
            }

        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        JSONObject json = null;
        String sucessvalue = null;
        String errorvalue=null;
        try {
            json = new JSONObject(result);
            sucessvalue = json.getString("Success");
            errorvalue=json.getString("Error");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(sucessvalue!=null) {

            Intent i = new Intent(SignIn.this, login.class);
            i.putExtra("sucessval", sucessvalue);
            startActivity(i);
        }
        else
            content.setText(result);
    }
}
}

我的php页面如下所示:

<?php
$fp=$_POST['firstParam'];
$sp=$_POST['secondParam'];
if($fp=='badhe.percept@gmail.com' && $sp=='badhe')
echo "{Success:'Hellooo...'}";
else
echo "{Error:'something happened'}";
?>

1 个答案:

答案 0 :(得分:3)

我正在使用this solution。它会将您的Cookie存储在您的共享偏好设置中。这可以防止您在应用关闭时丢失数据。

在应用的开头初始化它。

CookieManager cookieManager = new CookieManager(new PersistentCookieStore(getApplicationContext()),CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);