我有以下代码将登录详细信息发布到网站。它可以工作,但我怎么能有会话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();
}
}
}
}
答案 0 :(得分:2)
而不是创建新的DefaultHttpClient
,重用它。您的Cookie存储在DefaultHttpCilent
中,因此,如果您继续重复使用相同的实例,您的Cookie将自动为您处理。