You can add this code to your main activity - it will do all the heavy lifting for you.
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPostExecute(final Boolean success) {
if (success == true) {
//Do whatever your app does after login
} else {
//Let user know login has failed
}
}
@Override
protected Boolean doInBackground(String... login) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"YOUR_ADDRESS_HERE.COM");
String str = null;
String username = login[0];
String password = login[1];
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
return false;
}
try {
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
//Whatever parsing you need to do on the response
//This is an example if the webservice just passes back a String of "true or "false"
if (str.trim().equals("true")) {
return true;
} else {
return false;
}
}
You can create this object by:
UserLoginTask mAuthTask = new UserLoginTask();
Start the request with (perhaps put in an OnClick event from a login button?):
mAuthTask.execute(mUsername, mPassword);