I have a login form in Android that I want to use to send a HttpPost request to a server and get a cookie back in return if the login was successful. I have one problem how do I implement a correct version of this and how do I get the cookie and store it on the device (do I store it in the preference database? so I can destroy it later on?).
I have this code right now:
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://a_site.com/logintest.aspx");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("txtUsername", "username"));
nameValuePairs.add(new BasicNameValuePair("txtPassword", "123456"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.v(TAG, "Response from server: " + response.toString());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
How do I get the cookie and how do I store it if the login was successful?
The following code snippet will return a nicely formatted string representation of the http response:
How you choose to store the result is another question, I would suggest some sort of global variable.
Rather than writing your own, you can do it the easy way: