I recently made a question based on doing a HTTP request with POST data (Found here: Android API 14 – POST Data to HTTP) and I was told I would need to try something like an AsyncTask because I cannot carry out Network Operations in the main thread.
In short form, I have no idea how to do this. Any help is appreciated! Here is my code:
package me.babblebox.application;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class BabbleBoxActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void check_login() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://babblebox.me/android/test.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
public void check_login_button(View v) {
check_login();
}
}
Read about Processes and threads also AsyncTask.
The following is far from perfect but you could try something like this to get started…
In reality you’ll need to learn how to pass paramaters into the
AsyncTaskand get it to return valid results.EDIT:
Just out of interest, I put together your original code (without AsyncTask but on Android v2.2 which allows network operations on main thread). I added some logging code just to check the connection worked…
…and I got the following response headers.
The response from any web ‘request’ (GET, POST, PUT) will vary depending on the remote service you are talking to. You’ll need to work out what your server is going to return and then process the response accordingly.