0
我有以下代碼將登錄詳細信息發佈到網站。它的工作原理,但我怎麼能有會話cookie所以我不必再爲如何存儲cookie以便與HttpClient進行後續連接
編輯其他頁面登錄:更新的代碼
進口...
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();
}
}
}
}
我在類中全局聲明瞭httpclient,但現在當我嘗試第二次使用它時,它說它正在被第一個方法使用。當我做httpclient.getConnectionManager()。shutdown()然後第二個方法拋出和錯誤說管理器被關閉。我怎樣才能在一次通話後實現它,並將它交給另一種方法? – code511788465541441
@ user521180:步驟#1:在你的活動的'onCreate()'中創建'DefaultHttpClient'。第2步:在你的活動的onDestroy()中調用'getConnectionManager()。shutdown()'。步驟#3:如果你打算同時在多個線程中使用它,請附上http://hc.apache.org上記錄的'ThreadSafeClientConnectionManager'。步驟#4:根據需要使用'DefaultHttpClient'。 – CommonsWare
我已經用我整個班級的代碼形式更新了原始問題。你能告訴我怎麼做,以便'test0()'可以檢索數據以及 – code511788465541441