0

我有以下代码将登录详细信息发布到网站。它可以工作,但我怎样才能拥有会话 cookie,所以我不必再次登录其他页面

编辑:更新的代码

进口...

public class Login extends Activity {
    Button bLogin;
    EditText teUsername, tePassword;
    CheckBox chbRememberPass;

    HttpClient httpclient;
    HttpResponse response;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        initialiseVars();
        httpclient = new DefaultHttpClient();

        bLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                checkLoginDetails();
                test0();
            }
        });
    }

    private void initialiseVars() {
        bLogin = (Button) findViewById(R.id.bLogin);
        teUsername = (EditText) findViewById(R.id.etUsername);
        tePassword = (EditText) findViewById(R.id.etPassword);
        chbRememberPass = (CheckBox) findViewById(R.id.chkRememberPass);
    }

    private void checkLoginDetails() {


        HttpPost httppost = new HttpPost(
                "mywebsite/login.php");
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
        nameValuePairs.add(new BasicNameValuePair("username", "admin"));
        nameValuePairs.add(new BasicNameValuePair("password", "pass"));

        try {
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            Log.d("myapp", "works till here. 2");
            try {
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String responseBody = httpclient.execute(httppost, responseHandler);

                    Log.d("firstCon",responseBody);

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    private void test0() {

        HttpGet httppost = new HttpGet(
                "https://mywebsite/userSettings.php");

        try {
            response = httpclient.execute(httppost);
            //String responseBody = EntityUtils.toString(response.getEntity());         
            try {
                Log.d("secondCon", test());

            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.d("seconderror", e.toString());
            }


        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    }

}
4

1 回答 1

2

与其创建一个新的DefaultHttpClient,不如重用它。您的 cookie 存储在 中DefaultHttpCilent,因此如果您继续重复使用同一个实例,您的 cookie 将自动为您处理。

于 2012-05-19T14:44:32.910 回答