gpt4 book ai didi

java - 如何为后续与 HttpClient 的连接存储 cookie

转载 作者:行者123 更新时间:2023-12-02 07:47:08 26 4
gpt4 key购买 nike

我有以下代码,可将登录详细信息发布到网站。它可以工作,但我怎样才能拥有 session 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();
}

}

}

}

最佳答案

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

关于java - 如何为后续与 HttpClient 的连接存储 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10666110/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com