I found the following code to do a HTTP POST. It says me don’t run these code directly in UI/Main Thread. Create an AsyncTask and put the code in doInBackground method. How can make it run under asynctask.
String dataUrl = "http://example.com";
String dataUrlParameters = "email="+"pp@gmail.com"+"&name="+"priyabrat"+"&message="+"Message_here";
URL url;
HttpURLConnection connection = null;
try {
// Create connection
url = new URL(dataUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length","" + Integer.toString(dataUrlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(dataUrlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
String responseStr = response.toString();
Log.d("Server response",responseStr);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}