Send login using POST with Android!

I have an Android login form that I want to use to send an HttpPost request to the server and get the cookie back if the login was successful. I have one problem, how can I implement the correct version of this and how can I get a cookie and save it on the device (store it in the preferences database so that I can destroy it later?).

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 to get a cookie and how to save it if the login was successful?

+4
source share
2 answers

Instead of writing your own, you can do it in a simple way:

 import org.apache.http.util.EntityUtils; HttpResponse response = httpclient.execute(httppost); String responseAsText = EntityUtils.toString(response.getEntity()); 
+5
source

The following code snippet will return a well-formatted string representation of the HTTP response:

 public String responseHandler(HttpResponse response) { HttpEntity resEntity = response.getEntity(); br = new BufferedReader(new InputStreamReader( resEntity.getContent(), "UTF-8")); String line; String result = ""; while (((line = br.readLine()) != null)) { result = result + line + "\n"; } return result; } 

How you decided to save the result is another question, I would suggest some kind of global variable.

+2
source

All Articles